Simple Arrays in PHP

From Knowledge Kitchen
Jump to navigation Jump to search


Creating simple arrays

  • An array is simply a list of values.
  • Arrays are a convenient way to group related data.
  • All elements in an array consist of a key and its corresponding value.
  • Simple arrays use consecutive integers as the keys for all elements.


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

Array
(
    [0] => John
    [1] => Bob
    [2] => Sheila
)


A single statement specifying all the values

//FIRST WAY TO MAKE AN ARRAY WITH NUMERIC KEYS
$array1 = array("John", "Bob", "Sheila");


A single statement specifying all the keys and their corresponding values

//SECOND WAY TO MAKE AN ARRAY WITH NUMERIC KEYS
$array2 = array(
	0 => "John", 
	1 => "Bob", 
	2 => "Sheila"
);


Multiple statements specifying all the keys and their corresponding values

//THIRD WAY TO MAKE AN ARRAY WITH NUMERIC KEYS
$array3 = array();
$array3[0] = "John";
$array3[1] = "Bob";
$array3[2] = "Sheila";


A single statement relying on automatically-numbered keys, and specifying all their corresponding values

//FOURTH WAY TO MAKE AN ARRAY WITH NUMERIC KEYS
$array4 = array();
$array4[] = "John";
$array4[] = "Bob";
$array4[] = "Sheila";


Reading values out of an array

The keys in an array are pointers to their corresponding values.

/*
 * $array1[0] is a pointer to the string, "John"
 * $array1[1] is a pointer to the string, "Bob"
 * etc...
*/

echo $array1[1]; //outputs "Bob"
echo "Hi, " . $array1[0] . "!"; //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 ($array1 as $value) : ?> 
		<?php echo $value; ?>
<?php endforeach; ?>


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

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


Looping through an array the crude way

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


What links here