FreeKB - PHP Getting Started with Arrays
PHP - Getting Started with Arrays

Following are both valid examples of how to create an empty array (does not contain any values).

$foo = []; 
$foo = array();

 

In this example, an array named fruit contains different types of fruit.

$fruit = array("apple", "banana", "orange", "grapes");

 

var_dump can be used to print the data structure of the array.

var_dump($fruit);

 

Which will return the following. Notice that integers 0 1 2 3 are used as the key for each value in the array. If you want, you can define the keys.

array(4) { [0]=> string(5) "apple" [1]=> string(6) "banana" [2]=> string(6) "orange" [3]=> string(6) "grapes" }

 

Specific elements can be printed, like this.

echo "fruit[0] = " . $fruit[0] . "<br />";
echo "fruit[1] = " . $fruit[1] . "<br />";
echo "fruit[2] = " . $fruit[2] . "<br />";
echo "fruit[3] = " . $fruit[3] . "<br />";

 

Which will return the following.

fruit[0] = apple
fruit[1] = banana
fruit[2] = orange
fruit[3] = grapes

 

Or you can loop through the array.

foreach ($fruit as $value) {
  echo "$value<br \>";
}

 

Which will return the following.

apple
banana
orange
grapes

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter c2cdb in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |