PHP Arrays – Iterate the keys and values within an array

In this post we will be creating a PHP script that will iterate and print the keys and values within an array, arrays in PHP provide a means of storing multiple items in to a single variable.

See our array below for this example consisting of five items.

$array = array('James' => 23, 'Harry' => 19, 'Rahul' => 23, 'Leah' => 26);

To iterate the array and retrieve both the keys and values we make use of a ‘foreach’ construct, see the snippet of code below as an example. This makes use of a line break after each item, meaning each item will be printed on a new line.

<?php
$array = array('James' => 23, 'Harry' => 19, 'Rahul' => 23, 'Leah' => 26);

foreach ($array as $key => $value) {
	echo $key . " - " . $value. "<br>";
}

?>

The above would return the following as output.

James - 23
Harry - 19
Rahul - 23
Leah - 26

Leave a Reply