Associative Arrays in PHP

From Knowledge Kitchen
Jump to navigation Jump to search


Creating associative arrays

  • Associative arrays are a slight variant of simple arrays, so make sure you understand simple arrays.
  • The main difference is that the keys in associative arrays can be strings, whereas keys in simple arrays are integers.

The following examples each create identical arrays with string keys. In each example, the code produces an array with the following structure:

Array
(
    ['a'] => John
    ['b'] => Bob
    ['c'] => Sheila
)


A single statement specifying all the keys and their corresponding values

//SECOND WAY TO MAKE AN ARRAY WITH NUMERIC KEYS
$array2 = array(
	'a' => "John", 
	'b' => "Bob", 
	'c' => "Sheila"
);


Multiple statements specifying all the keys and their corresponding values

//THIRD WAY TO MAKE AN ARRAY WITH NUMERIC KEYS
$array3 = array();
$array3['a'] = "John";
$array3['b'] = "Bob";
$array3['c'] = "Sheila";

Reading values out of an array

Like in simple arrays, the keys in an array are pointers to their corresponding values.

/*
 * $array2['a'] is a pointer to the string, "John"
 * $array2['b'] is a pointer to the string, "Bob"
 * etc...
*/

echo $array1['b']; //outputs "Bob"
echo "Hi, " . $array2['a'] . "!"; //outputs "Hi, John!"


Looping through simple arrays

The foreach structure allows you to loop easily through all elements in a given array.

Looping through an array and accessing only the values

<?php foreach ($array2 as $value) : ?> 
		<?php echo $value; ?>
<?php endforeach; ?>


Looping through an array and accessing both the keys and the values

<?php foreach ($array2 as $key => $value) : ?>
		<?php echo $key; ?> <?php echo $value; ?>
<?php endforeach; ?>


Looping through an array the crude way

<?php for ($i=0; $i<sizeof($array2); $i++) : ?>
		<?php echo $array1[$i]; ?>
<?php endfor; ?>


What links here