9 PHP Array Mistakes That Developers Make

PHP Arrays are very handy to implement ordered lists, maps (also called associative arrays), as well as combinations of the two (ordered maps).

Arrays are very easy to use, but there are a few things you need to pay attention to.

So, here are 9 common mistakes that developers make with PHP arrays.

(Are you new to PHP and you want to learn about arrays and other basic PHP functionalities as quickly as possible? Take a look at my beginners’ course to get started).

Contents:

#1: Assuming that an array key is always set.
#2: Assuming that the array’s order is defined by the key.
3: Not using strict comparison with current() and next().
#4: Using numeric strings, floats or Booleans for array keys.
#5: Using strict comparison on numeric string keys in foreach loops.
#6: Using arrays instead of iterables for ordered lists.
#7: Assuming that keys are rearranged when an array element is removed.
#8: Using references in foreach loops to change the array’s values.
#9: Using isset() instead of array_key_exists().

#1: Assuming that an array key is always set.

A common mistake is to assume that all the array keys that you expect are actually set.
This happens, for example, with the request string array, when you access the $_GET, $_POST or $_REQUEST arrays without verifying the key existence first.

For example:

$name = $_GET['name'];
echo 'Hello, ' . htmlentities($name);

This code gives you a warning if you call the script without a “name” request element.

To avoid warnings and coding bad practices, make sure to check that the key exists before trying to access the element:

if (array_key_exists('name', $_GET)) {
   $name = $_GET['name'];
   echo "Hello, " . htmlentities($name);
}
else {
   echo 'Please tell me your name.';
}

The same rule also applies to arrays created from other sources, such as JSON packets and database result sets.

Verifying that an array key is set is important for security too.
Failing to do so can result in harmful data being used in your application or, even worse, in SQL queries.
If you want to learn exactly how to perform this validation, take a look at my professional PHP Security course.

#2: Assuming the array’s order is defined by the key.

PHP Arrays are always ordered, but the order is not given by the key. It is given by the order of insertion.

When you iterate through an array, the iteration order is the same as the insertion order, regardless of the keys used.

For example, the element with key 3 is the last one because it is the last added to the array, even if its key numeric value (3) is not the highest:

$array = array();
$array[0] = 'A';
$array[1] = 'B';
$array[2] = 'C';
$array[4] = 'E';
$array[5] = 'F';
$array[3] = 'D';
foreach ($array as $value) {
   echo $value . ' ';
}
// Output: A B C E F D

#3: Not using strict comparison with current() and next().

The current() and next() functions return false when the array internal pointer reaches the end.

When you check that the return value is false you must use strict comparison, otherwise other values such as 0 or the empty string will satisfy the condition.

For example, the following loop stops at the element “0”:

$array = [1, 7, 3, 0, 4, 9, 2];
while ($val = current($array)) {
   echo $val . ' ';
   next($array);
}
// OUTPUT: 1 7 3

If you use strict comparison instead, then the loop goes on correctly:

while (($val = current($array)) !== false) {
   echo $val . ' ';
   next($array);
}
// OUTPUT: 1 7 3 0 4 9 2

#4: Using numeric strings, floats or Booleans for array keys.

When you specify the key for an array element, PHP automatically casts Booleans, floats and numeric strings to integers.
This makes using those types for keys problematic, as well as making the code poorly readable.

(Using floats for array keys is also deprecated).

For example, here the first three elements gets overridden by last three:

$array = [
   TRUE => 'First element',
   3.21 => 'Second element',
   "9" => 'Third element',
   1 => 'Fourth element', // overrides TRUE
   3 => 'Fifth element', // overrides 3.21
   9 => 'Sixth element' // overrides "9"
];
print_r($array);
Array ( [1] => Fourth element [3] => Fifth element [9] => Sixth element )

#5: Using strict comparison on numeric string keys in foreach loops.

Since numeric strings are converted to integers when used as keys, you cannot use strict comparison on string keys, because numeric strings are going to be casted to integers and fail the comparison.

For example, in the following loop only the key “string” is found, but the key “2” is not because it is converted into the integer value 2:

$array = [
   'string' => 'A',
   '2' => 'B'
];
foreach ($array as $key => $value) {
   if ($key === 'string') {
      echo 'Key "string" found!'; // This is found.
   }
   
   if ($key === '2') {
      echo 'Key "2" found!'; // This is never found, because "2" has become 2.
   }
}

#6: Using arrays instead of iterables for ordered lists.

As explained in this cool article, if what you need is an ordered list then you should use an Iterable object instead of an array.
Iterables include arrays as well as other objects such as generator functions, making your code more usable.

For example, the following function works with both arrays and Iterables:

function sumSequence(iterable $sequence, int $n): float {
   $sum = 0;
   $count = 0;
   
   foreach ($sequence as $val) {
      $sum += $val;
      $count++;
      
      if ($count > $n) {
         return $sum;
      }
   }
   
   return $sum;
}

#7: Assuming that keys are rearranged when an array element is removed.

Let’s say that you have a numeric array:

$array = [
   0 => 'apple',
   1 => 'banana',
   2 => 'pear',
   3 => 'coconut'
];

If you remove an element from the array, the keys will not be rearranged. Instead, the key of the removed element will simply not be set anymore.

For example:

unset($array[2]);
for ($i = 0; $i < 3; $i++) {
   echo $array[$i] . '<br>';
}
apple
banana
Warning: Undefined array key 2 in C:\xampp\htdocs\test.php on line 14

#8: Using references in foreach loops to change the array’s values.

You can change the value of an array’s element in a foreach loop by using references on the foreach value variable.

For example:

$array = [
   0 => 'apple',
   1 => 'banana',
   2 => 'pear',
   3 => 'coconut'
];
foreach ($array as &$value) {
   $value .= ' fruit';
}
print_r($array);
Array ( [0] => apple fruit [1] => banana fruit [2] => pear fruit [3] => coconut fruit )

This works, however it leaves a dangerous reference laying around that, as explained in this article, can cause unexpected problems.

When you want to change the array’s values, it is better to use the key => value syntax instead:

foreach ($array as $key => $value) {
   $array[$key] .= ' fruit';
}

#9: Using isset() instead of array_key_exists().

How do you check if an array’s key is set?

The proper way to do that is to use the array_key_exists() function:

$array = [
   0 => 'apple',
   1 => 'banana',
   2 => 'pear',
   3 => 'coconut'
];
if (array_key_exists(2, $array)) {
   echo "Key 2 exists, its value is: " . $array[2];
}
else {
   echo "Key 2 does not exist in the array.";
}
// Output: Key 2 exists, its value is: pear

You may be tempted to use isset() instead, because of its easier syntax.

However, isset() will not recognize array keys with a NULL value associated with them.

For example:

$types = [
   'int' => 1,
   'string' => 'hi',
   'Bool' => true,
   'null' => NULL
];
if (!isset($types['null'])) {
   echo 'null type does not exist';
}
// Output: null type does not exist

And that’s it.

Let me know if you have any questions by leaving a comment below.

Alex

Leave a Comment