Contents
PHP array Functions: Main Tips
- Introduced in PHP 4, it creates an array of the specified parameters.
- A PHP array functions as a variable that holds multiples values.
- There are 3 types of PHP arrays: indexed (numeric index), associative (named keys) and multidimensional (multiple arrays in one).
Usage of array()
You could call array()
the base of all PHP array functions. To put it shortly, it is used to create an array. Let's see a simple example:
<?php
$food = ['IceCream', 'Pizza', 'Burger'];
echo "I like " . $food[0] . ", " . $food[1] . " and " . $food[2] . ".";
?>
Correct Syntax
You are probably aware that it's crucial to pay attention to correct syntax when coding, and it's no different when you're using PHP array functions. Let's see how a piece of script should be written for an indexed array:
array(value1,value2,value3,...);
Now, for the associative array PHP syntax is a bit different. They can also be called PHP key value arrays, as pairs of keys and values define them. Note that either numbers or a string can represent the key:
array(key=>value,key=>value,key=>value,...);
In both cases of using PHP array functions, value
elements define each value an array contains to make PHP create array.
In the short version of array syntax introduced in PHP 5.4, array()
can be replaced with []
. For example, instead of $food=array("IceCream","Pizza");
you can simply type $food=["IceCream","Pizza"];
to make PHP create array. It will not change the way the new PHP array functions.
Practice: Code Examples
The code in the example below creates an associative array PHP script refers to as $age
:
<?php
$age = [
'Drago' => 69,
'Mark' => 32,
'Luke' => 35
];
echo "Mark is " . $age['Mark'] . " years old.";
?>
If we wanted to execute an associative array PHP loop and print its values, our code would look like this:
<?php
$food = [
'Pizza' => 5.90,
'IceCream' => 1.90,
'Burger' => 2.90
];
foreach($food as $z => $z_value) {
echo "Key=" . $z . ", Value=" . $z_value;
echo "<br>";
}
?>
Now, the script in this example loops through an indexed array and prints its values:
<?php
$food = ['IceCream', 'Pizza', 'Burger'];
$arrayLength = count($food);
for($z = 0; $z < $arrayLength; $z++) {
echo $food[$z];
echo "<br>";
}
?>
Note: when looping though arrays, choose for and foreach loops.
Now, let's see how creating a multidimensional array would look like:
<?php
// A two-dimensional array
$food = [
['IceCream', 50, 32],
['Pizza', 40, 39 ],
['Burger', 35, 20 ]
];
echo $food[0][0].": Ordered: ".$food[0][1].". Sold: ".$food[0][2]."<br>";
echo $food[1][0].": Ordered: ".$food[1][1].". Sold: ".$food[1][2]."<br>";
echo $food[2][0].": Ordered: ".$food[2][1].". Sold: ".$food[2][2]."<br>";
?>