- PHP scripts can create arrays to hold data elements. The following example PHP code demonstrates creating an array variable and adding a series of elements to it at the same time:
$people=array("Jim", "Barbara", "Sam");
The array structure contains three elements, each a text string indicating a person's name. The PHP script can now process the array, including accessing the elements within it, iterating through it and optionally writing out information about it in HTML markup. - PHP scripts can output information to the user's browser in a number of ways. The "print_r" function outputs information about a program variable, formatted in a way that makes it readable to humans. The following example code demonstrates writing the array using this technique:
print_r($people);
This method is generally used for testing and development, but for user output, the echo command provides the ability to write HTML structures and other content. The following code demonstrates use of the echo function to write the value of a variable within an HTML element:
$some_value = "hello";
echo "<p>".$some_value."</p>"; - If a Web page needs to output the value of a single array element in HTML, the following syntax provides this ability:
echo "<div>".$people[2]."</div>";
This code outputs the value of the element at position two within the array. The position index could also exist as a variable as follows:
$posn = 2;
echo "<div>".$people[$posn]."</div>";
This code uses an HTML "div" element, with the opening and closing tags appearing before and after the array element value. You can include any HTML markup you need as part of an echo statement within a PHP script. - To output each item within a PHP array using tailored markup code, PHP scripts use loops. The following example code demonstrates a "for each" loop, iterating through the array and outputting each element within an HTML paragraph element along with some other text:
echo "People:<br/>";
foreach ($people as $value) {
echo "<p>".$value."</p>";
}
The "for each" loop carries out the processing specified for each element in the array indicated. The code refers to each element in turn using the "value" variable, which represents the element at the current array position on each iteration, moving along until it has exhausted the array.
Array Creation
HTML Output
Individual Elements
Entire Array
SHARE