By using this site you agree to the use of cookies.

Learn more

Share via:

PHP: Arrays

This tutorial explains how arrays may be created in PHP, and what they can be used for.

Edited: 2017-04-30 16:16

PHP article image

Arrays makes it easy to associate elements (values) with keys. The individual values can then be re-called later in a script.

Arrays are useful in many situations, but a common use is when you need to work dynamically on a set of elements. They are also easier to pass on to functions than variables.

Sometimes, if a function accepts a lot of parameters, passing them as an array might make more sense, and even avoid problems with unused parameters.

Creating arrays

In PHP, arrays may be created in a number of ways. One of the most memorable ways to create an array is like done below:

$MyArray = array();
$MyArray[] = 'Peter';
$MyArray[] = 'John';
$MyArray[] = 'Matthew';

The above code would automatically assign a key to each value we place in the array, and it is easy to add more elements as needed. We may also assign a key manually. An array key can either be an integer or a string, in the above example a integer is assigned for each element, beginning with "0".

Tip. If a string key is very long, it may sometimes help to use a hash of the string instead. Though, there is no limit on allowed characters.

Assigning a key manually is easy, simply do like this:

$MyArray = array();
$MyArray['name'] = 'Peter';
$MyArray['phone'] = '20170315';
$MyArray['email'] = 'peter@beamtic.com';

Another common way to create an array, which may be somewhat harder to remember:

$MyArray = array(
    "name" => "Peter",
    "phone" => "20170315",
);

Determining the length of an array

Counting elements in an array can be done using the PHP count function:

<?php
$aCoolStuff['php'] = "PHP is Cool";
$aCoolStuff['css'] = "CSS is Cool";
$aCoolStuff['html'] = "HTML is Cool";

echo count($aCoolStuff); // 3
?>

If the second parameter, mode, of the count function is used, the function can be made to work recursively, allowing us to count elements in multidimensional arrays:

<?php
$aMyPHPArray[0] = "Key1 content";
$aMyPHPArray[1] = array(
  'SubKey1' => 'SubKey1 content',
  'SubKey2' => 'SubKey2 content');
$aMyPHPArray[2] = "Key2 content";

 $n = count($aMyPHPArray, 1); // Number of elements in array

echo $n; // returns 5
?>

Iterate over arrays

Looping through arrays can be done using a while loop, after first determining the length of the array. Or, if you do not know the length of the array, by using a foreach loop.

A foreach loop is likely the simplest way to iterate over arrays in PHP, and it can also be used on objects.

<?php
$MyArray = array();
$MyArray[0] = 'One';
$MyArray[1] = 'Two';
$MyArray[2] = 'Three';

foreach ($MyArray as &$value) {
    echo $value . '<br>';
}
?>

To get both the key and the value:

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

A while loop may be used when the length of the array is known, and a $counter variable is used to manually keep track of the position in the array.

$MyArray[0] = 'One';
$MyArray[1] = 'Two';
$MyArray[2] = 'Three';

 $n = count($aMyArray); // Count the number of Elements in array

 $counter = 0; // Initialize the counter variable
 while ($counter < $n) {
   echo $aWords["$counter"] . '<br>';
   ++$counter; // Increment the counter by 1
 }

Searching for keys in arrays

To check for the existence of certain array keys, we may use the isset, and array_key_exists functions.

A simple way to check if a given key exists, is to use PHP's isset function. I.e.:

<?php
if (isset($MyArray["2"])) {
 echo 'Found';
} else {
 echo 'Not Found';
}
?>

Note. isset will not work with certain key names. NULL and 0 will return false, even when they do exist.

Another way to check for keys, which avoids the problem with isset, is with the array_key_exists function:

if (array_key_exists(3, $MyArray)) {
 echo 'Found';
} else {
 echo 'Not Found';
}

Search array for values and return keys

You can search an array for a value using PHP's in_array, while array_search can be used to return the key name of an element. To check for the existence of a string or number, simply do like this:

<?php
$aMyTest = array("MyTest1", "MyTest2", "MyTest3", "MyTest4");

if (in_array("MyTest2", $aMyTest)) {
    echo "Found MyTest2" . "<br>";
}
if (in_array("MyTest5", $aMyTest)) {
    echo "Found MyTest5";
} else {
    echo "MyTest5 not found in array!";
}
?>

You may obtain the key name itself using array_search:

<?php
$aMyTest = array();
$aMyTest[0] = 'red';
$aMyTest[1] = 'green';
$aMyTest[2] = 'blue';

$key = array_search('green', $aMyTest); // Outputs: 1
echo $key;
?>