PHP Associative Arrays

·

1 min read

Associative arrays are arrays where we pair a key with a value, each key in the array gives a value let's see an example:

here we have an array of books where we have two books, and each book is represented with an array, inside the array we have key and value pairs, the keys are name, author and purchaseUrl.

To loop over associative arrays we do the following: we specify the name of the book and the key we want to print, for example $book['name'] or $book['author'] or $book['purchaseUrl']

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <title>Demo</title>
</head>
<body>

<?php
$books=[
        [
                'name'=>'Do Androids Dream of Electric Sheep',
                'author'=>'Philip K. Dick',
                'purchaseUrl'=>'http://example.com'

        ],
    [
        'name'=>'Project Hail Mary',
        'author'=>'Andy Weir',
        'purchaseUrl'=>'http://example.com'
    ]

];
?>

<ul>
    <?php foreach ($books as $book) : ?>
    <li>
        <a href="<?php $book['purchaseUrl'];  ?>">
    <?=$book['name']; ?>
        </a>
    </li>
    <?php endforeach; ?>
</ul>


</body>
</html>