PHP Arrays Basics

Chapter 27 41 mins

Learning outcomes:

  1. A quick recap of arrays in PHP
  2. Adding elements to arrays
  3. Removing elements using array_pop() and unset()
  4. What are associative arrays
  5. Array operators (+, ==, ===, !=, !==)
  6. Searching elements in an array

A quick recap

So far in this course, we've encountered arrays on numerous occassions. Before we dive into exploring more details related to arrays in PHP in this chapter, let's quickly get a recap of all the concepts that we already know.

First things first:

An array in PHP is a collection of elements.

An array simply serves to hold a collection of one or more values in PHP under one logical unit.

This collection might be indexed or it might be associative (more on that later in this chapter).

An indexed array is an ordered collection of elements, whereby the position of each element is referred to as the index of that element. Indexes begin at 0 and increase by 1. Hence, the first element has the index 0, the second element has the index 1, and so on.

The total number of elements in an array is referred to as its length. For example, if an array has 10 elements, its length is 10.

To create an indexed array in PHP, we use a pair of square brackets ([]), including each value (or element) that we want in the array within these brackets. This is typically known as bracket notation. Multiple values are separated using a comma (,).

In the following code, we create an array holding the first five positive integers:

<?php

$nums = [1, 2, 3, 4, 5];

There is no hard and fast rule tied to the spacing inside an array in source code. We can format the elements in any way as we like.

When each element of an array is large enough to warrant a long line of code given that we write all the elements in a single line, it's a common approach to write each element on a new line, and the opening ([) and ending (]) brackets on a new line as well.

Shown below is an illustration:

<?php

$cities = ['London', 'Tokyo', 'Toronto', 'Beijing', 'Bangkok', 'Delhi', 'Seattle'];

The long city names have surely taken the entire line of code quite far away to the right. Following the approach specified above, we could rewrite this more neatly like this:

<?php

$cities = [
   'London',
   'Tokyo',
   'Toronto',
   'Beijing',
   'Bangkok',
   'Delhi',
   'Seattle'
];

The [, ] and each element of the array are on separate lines. Clearly much more readable.

The count() function is used to obtain the length of an array. It returns back an integer indicating the length:

<?php

$nums = [1, 2, 3, 4, 5];

echo count($nums);
5

Moving on, trying to print an array using the echo statement doesn't produce a sensible representation — only the text 'Array' is printed. Moreover, a warning message is also shown.

Consider the following:

<?php

$nums = [1, 2, 3, 4, 5];

echo $nums;
Warning: Array to string conversion in <file> on line 4 Array

In order to produce a more sensible output for a given array, we can turn to the print_r() function provided by PHP.

Let's try it:

<?php

$nums = [1, 2, 3, 4, 5];

print_r($nums);
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )

Each element is clearly depicted along with its index. Definitely much more sensible.

Now creating an array and then forgetting about it is almost never ever the case; we always want to work with elements stored in the array. That is, we want to retrieve them and possibly even modify them.

In order to retrieve a given element from an indexed array, we once again use bracket notation. The array whose element we want to access is written first, followed by a pair of square brackets ([]), and then within these we specify the index of that element.

Syntactically, something as follows:

arr[index]

where arr is an entity holding an array while index is an integer specifying the index of the element to be retrieved.

Besides this, if we want to change a particular element of an array to a new value, we have use the assignment operation (=), similar to how we change the value of a variable.

Here's the syntax for it:

arr[index] = new_value

The element is accessed in the same way in which we access it for reading, i.e. as arr[index], and then follow it by the assignment operator (=), which is obviously followed by the value to assign.

Let's take a quick example. Say we want to output the first and the fifth elements of the $nums array shown above, and modify the second element by multiplying it by 10, and then output it as well. Here's how we'll do that:

<?php

$nums = [1, 2, 3, 4, 5];

echo $nums[0], "\n";
echo $nums[4], "\n";

$nums[1] *= 10;
echo $nums[1], "\n";
1 5 20

First we access and output the first and fifth element of $nums, respectively, before modifying the second element and then outputting that as well.

Recall that $nums[1] *= 10 is the same as $nums[1] = $nums[1] * 10. =* is definitely shorter than having to type out the entire assignment expression using $nums[1] and *. For a review, head over to PHP Operators — Assignment.

To check whether an arbitrary value in PHP is an array, we use the is_array() function. It returns back a Boolean specifying whether or not the given value is an array:

<?php

$nums = [1, 2, 3, 4, 5];

var_dump(is_array($nums));
var_dump(is_array(10));
var_dump(is_array('Hello'));
bool(true) bool(false) bool(false)

Furthermore, iteration over an array is customarily done using two constructs: for and foreach.

In the following code, we iterate over $nums using for:

<?php

$nums = [1, 2, 3, 4, 5];

for ($i = 0, $len = count($nums); $i < $len; $i++) {
   echo $nums[$i], " ";
}
1 2 3 4 5

Similarly, in the following code, we do so using foreach:

<?php

$nums = [1, 2, 3, 4, 5];

foreach ($nums as $num) {
   echo $num, " ";
}
1 2 3 4 5

As you can see, foreach is much simpler than for. We don't have to worry about keeping track of the current element's index, computing the array's length, and setting up a loop condition — foreach handles everything by itself.

foreach can even be used to access each element of an array by-reference. We learnt this back in the PHP Control Flow — foreach chapter.

In the code below, utilizing foreach, we modify $nums by doubling each element and then print the array to confirm that it has really changed:

<?php

$nums = [1, 2, 3, 4, 5];

foreach ($nums as &$num) {
   $num *= 2;
}
print_r($nums);
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )

And it sure has!

With this, we complete our quick recap of all that we've learnt thus far in this course regarding arrays in PHP.

We have a really decent foundation on arrays, and so what we'll be doing in this chapter is build on top of that strong foundation and learn about other key concepts underlying this paramount data type in PHP, starting with how to add/remove elements after an array has been created.

Adding elements

Quite often, it's required to add elements to an array after it has been created.

For instance, if we want to obtain 10 numbers from standard input and then process them together, it's a good idea to store them inside an array. And this means that we begin with an empty array, adding each number to it as it's input.

To add elements to an array in PHP, we have a couple of options:

  1. Assign to the index where a new element is desired to be added.
  2. Use option 1 without specifying an index.
  3. Use the array_push() function.

Manually assign to an index

We learnt above that accessing a non-existent index on an array results in a semantic error in PHP. However, if we manually assign to such an index, we don't get an error and end up adding a new element to the array.

Suppose we have the following $nums array and want to add -17 to it, right at its end:

<?php

$nums = [10, 5, 9, 6, 12];

The last element's index is 4, and so we need to add -17 on index 5. Here's how we'd do that:

<?php

$nums = [10, 5, 9, 6, 12];

// Add -17 at the end of $nums.
$nums[5] = -17;

print_r($nums);
Array ( [0] => 10 [1] => 5 [2] => 9 [3] => 6 [4] => 12 [5] => -17 )

The assignment surely results in -17 being added to $nums, but it comes at a cost — flexibility.

If we modify the original $nums array by changing the number of elements stored, we'd have to manually figure out the index of the last element and then update our assignment statement with the corresponding next index. As you'd agree, this is error-prone and not flexible at all.

A better option is to use count() for this purpose, as demonstrated below:

<?php

$nums = [10, 5, 9, 6, 12];

// Add -17 at the end of $nums.
$nums[count($nums)] = -17; print_r($nums);

The length of an array is always 1 greater than the index of its last element. Therefore, using count() in place of a hard-coded index is flexible.

But if we want to do this over and over again, our code would start to look pretty ugly:

<?php

$nums = [10, 5, 9, 6, 12];

// This doesn't look elegant :(
$nums[count($nums)] = -17;
$nums[count($nums)] = -9;
$nums[count($nums)] = 100;
$nums[count($nums)] = 50;
$nums[count($nums)] = 10;

For these reasons, it's NOT recommended to use this option ever in code when using indexed arrays. It's only shown here to clarify as to which methods are possible in PHP to add an element to an indexed array.

Anyways, this method of manual assignment is meant for adding elements to an associative array (which doesn't have sequential keys as in indexed arrays). We'll learn more about associative arrays in the following sections in this chapter.

Assignment without an index

PHP puts forward a special syntax to add an element to (the end of) an indexed array. That is, we use assignment just like we'd use it to add an element to a particular index, but this time we omit the index.

Syntactically, like the following:

array[] = value

What this does behind-the-scenes is that it takes the last element's index of the array, and performs the assignment to the next index.

Going with the example above, here's how we'll add -17 to the $nums array using this syntax:

<?php

$nums = [10, 5, 9, 6, 12];

// Add -17 at the end of $nums.
$nums[] = -17;

Without a doubt, this is much better than manually assigning to the next index.

And what's even better is that it keeps the code serene when we ought to perform many such additions, as shown below:

<?php

$nums = [10, 5, 9, 6, 12];

// This does look elegant :)
$nums[] = -17;
$nums[] = -9;
$nums[] = 100;
$nums[] = 50;
$nums[] = 10;

Starting from now, we'll use this syntax throughout the rest of this course to add elements at the end of a given array.

Using array_push()

Another way to add elements to the end of an array is via the array_push() function.

The main benefit of using array_push() is when we need to bulk-add a lot of elements at once.

What does 'push' mean in array_push()?

The name 'push' in array_push() actually originates from the stack data structure in computer science. A stack is a collection of data, just like an array, except for that it behaves akin to stacks in real life, such as a stack of plates.

Two common operations performed on stacks are called 'push' and 'pop'.

The push operation 'pushes', i.e. adds, an element on top (which is the end) of the stack, while the 'pop' operation removes the top element from the stack.

As we shall see in the upcoming chapter, PHP Array Functions, there is even a function to perform the 'pop' operation on arrays. That is array_pop().

Here's the syntax of the function:

array_push($array, $value_1[, $value_2[, ...[, $value_n]]])

The first argument is the array where we want to add stuff. The rest of the arguments each represent a value to be added to the array in the same order they appear in here.

Shown below is an example:

<?php

$nums = [10, 5, 9, 6, 12];

// Add -17 at the end of $nums.
array_push($nums, -17);

print_r($nums);
Array ( [0] => 10 [1] => 5 [2] => 9 [3] => 6 [4] => 12 [5] => -17 )

As specified in the documentation of array_push(), if we ought to add a single element to an array, it's recommended to use option 2 above, i.e. array[] = value.

Firstly, it's shorter and easier to type. Secondly, it's more efficient than array_push() since it doesn't involve a function call.

As a rule of thumb, use array_push() only when the need is to add more than one element to an array in one go. Otherwise, just use array[] = value. Simple.

And let's now see how to bulk-add elements to an array using array_push():

<?php

$nums = [10, 5, 9, 6, 12];

array_push($nums, -17, -9, 100, 50, 10);

print_r($nums);
Array ( [0] => 10 [1] => 5 [2] => 9 [3] => 6 [4] => 12 [5] => -17 [6] => -9 [7] => 100 [8] => 50 [9] => 10 )

As is evident, the 5 numbers passed on to array_push() get added to the end of $nums in the exact same order in which they're provided to the function as arguments.

Removing elements

To remove an element from an array in PHP, we have a great deal of options. The removal could be done from either the end of the array, from its start, or from a specific position. Even bulk-removal is possible, whereby multiple elements are deleted all at once.

To keep things square for now, we'll consider just two options to remove elements and that from the end of an array:

  1. The array_pop() function.
  2. The unset() function.

The array_pop() function

The array_pop() function is used to perform the 'pop' operation on an array, i.e. remove the last element. It returns back the removed element, so in case we ought to use it, we can easily do so.

The syntax of array_pop() is extremely simple — just provide it with the array whose last element is to be removed:

array_pop($array)

It's time for an example.

In the following code, we call array_pop() on $nums, save its return value in $removed and then print both the array and the removed value:

<?php

$nums = [10, 5, 9, 6, 12];

$removed = array_pop($nums);

print_r($nums);
echo "Removed element: $removed";
Array ( [0] => 10 [1] => 5 [2] => 9 [3] => 6 ) Removed element: 12

Notice how the array has been ridden off from its last element.

array_pop() is often used alongside a while loop in order to process the contents of an array.

The idea is that we start from the end of the array, going towards its beginning, and keep removing each and every element therein before processing it in the loop's body. Such an operation is customary for processing (and emptying) a stack. (Remember what's a stack?)

Shown below is an example:

<?php

$nums = [10, 5, 9, 6, 12];

while (count($nums)) {
   $num = array_pop($nums);
   echo "Removed element: $num\n";
}
Removed element: 12 Removed element: 6 Removed element: 9 Removed element: 5 Removed element: 10

We keep removing the last element of $nums as long as count($nums) returns some non-zero integer, i.e. $nums still has elements in it.

Because, in the loop, we call array_pop($nums), which reduces the length of an array, the loop's condition count($nums) is bound to produce 0 at some point. And when that happens, the loop would complete and $nums would be empty.

The unset() function

Recall the unset() function from previous chapters? It can be used to remove variables from a particular context.

Fortunately, it can also be used to remove a specific element from an array. Here's how to use it:

unset($array[index])

In our case, since we're interested in removing the last element from an array, index here would simply be the index of the last element.

Consider the following code:

<?php

$nums = [10, 5, 9, 6, 12];

// Remove the last element.
unset($nums[count($nums) - 1]);

print_r($nums);

The index of the last element of an array is simply 1 less than its length. Consequently, to make our unset() call flexible (just as we did before), we leverage the count() function in it.

As you'd agree, although the code above works, using unset() is harder than array_pop() and something that we'll avoid when removing the last element of an indexed array.

Do keep in mind that unset() can be used to remove any element from an indexed array. And when this happens, the elements following it are NOT shifted back to account for the removed element. This make sense because this deletion method has been designed to work with associative arrays (more on that later), not really for indexed arrays.

For example, in the code below, when we call unset($nums[1]), the second element of $nums is deleted, and we're left with four elements at the indexes 0, 2, 3 and 4, respectively:

<?php

$nums = [10, 5, 9, 6, 12];

unset($nums[1]);

print_r($nums);
Array ( [0] => 10 [2] => 5 [3] => 6 [4] => 12 )

Notice the indexes — they cease to form a contiguous sequence. This is something to look our for when using unset() to delete elements in an indexed array.

If we really want to delete an element at a particular position in an indexed array, and make sure that shifting occurs thereafter, array_splice() is what we need. We'll take a look at it in the PHP Array Functions chapter.

Associative arrays

PHP has two different kinds of arrays: indexed (or numeric) and associative. So far uptil this point, we've only been dealing with indexed arrays. But now it's time to explore the latter kind.

So what are associative arrays in PHP?

An associative array is a collection of key-value pairs.

It's meant to be used to store a collection of data where we have some traits/characteristics and their corresponding values. The keys model the traits while the values model their values.

Here's how to initialize an associative array:

[key_1 => value_1, key_2 => value_2, ..., key_n => value_n]

In a more readable way, it's the same as:

[
   key_1 => value_1,
   key_2 => value_2,
   ...,
   key_n => value_n
]

The => symbol serves to draw the key-value relationship between two values — the value on the left specifies the key whereas the value on the right specifies the value of that key.

If you have experience of working in JavaScript before (which is quite probable), a literal object in JavaScript is pretty much the same thing as an associative array in PHP — in both cases, we have keys mapping to given values.

There are two things to note regarding keys in associative arrays:

  • Keys can only be integers or strings. If we have a key of a different data type, PHP will automatically coerce it into an appropriate integer or string, depending on the key.
  • Keys are supposed to be unique. We can't have two similar keys in an associative array. In case we have them, the value of the second key would override that of the first one.

In conversation involving associative arrays, to easen the terminology, key-value pairs are sometimes just collectively referred to as elements.

Once an associative array is created, accessing and modifying elements happens the same way we are used to do with indexed arrays. That is, we access an element via array[key] and modify it via array[key] = value.

Indexed arrays are also collections of key-value pairs!

Precisely speaking, the definition above also holds for indexed arrays in PHP. Yes, that's right. Indexed arrays are also collections of key-value pairs in PHP.

This might seem counter-intuitive. How can an indexed array be a collection of key-value pairs; isn't it a collection of values only? Precisely, no.

Well, the thing is that, internally, both kinds of arrays are represented in the exact same way. Each element in an indexed array also represents a key-value pair, where the key is its numeric index (which is an integer).

So when we do the following:

<?php

$nums = [10, 7, 8];

we are actually creating an array like the following:

<?php

$nums = [0 => 10, 1 => 7, 2 => 8];

It's just that PHP does this automatically behind-the-scenes so that we don't have to go through this tedious key-value syntax while initializing indexed arrays.

Henceforth, almost all what we've learnt thus far regarding indexed arrays also applies to associative arrays. That is, the syntax to read/write elements, determining the length of the array, adding elements, removing elements, pretty much everything is the same.

And that's good news. We don't have to learn anything new!

Let's consider a real-world scenario of using an associative array.

Suppose we have scanned a large piece of text and want to store the count of three words 'as', 'is' and 'us' in an array.

One way is to use an indexed array where we assert that the first, second and third elements represent the word counts of the aforementioned words, in that very order:

<?php

// The word counts of 'as', 'is' and 'us'.
$word_counts = [10, 88, 16];

But this is error-prone and not at all flexible. We have to always keep in mind that the second element, for example, represents the count of 'is'; this crucial piece of information is missing from the program itself.

Another option is to use two arrays, one holding the words and one holding their corresponding counts, as follows:

<?php

$word_names = ['as', 'is', 'us'];
$word_counts = [10, 88, 16];

Definitely better. The program can easily determine which word count corresponds to which word, but there still are limitations.

If we want to, let's say, determine the count of 'is', we have to first search for it in the $word_names array and then use the obtained index to query the $word_counts array. That's a lot of work!

What we really need here is an associative array.

Let's create one:

<?php

$word_counts = [
   'as' => 10,
   'is' => 88,
   'us' => 16
];

The keys here represent words while their values represent the counts of those words.

What's remarkable is that in order to determine the count of a particular word in the associative array above, we just need to use the array[key] syntax as shown below; no searching needed:

<?php

$word_counts = [
   'as' => 10,
   'is' => 88,
   'us' => 16
];

echo 'a: ', $word_counts['as'];

Perfect!

Let's play around with $word_counts using ideas that we already know regarding indexed arrays in PHP:

<?php

$word_counts = [
   'as' => 10,
   'is' => 88,
   'us' => 16
];

// Ten more occurrences of 'as' found.
$word_counts['as'] += 10;

echo 'Length: ', count($word_counts), "\n";
print_r($word_counts);
Length: 3 Array ( [as] => 20 [is] => 88 [us] => 16 )

Simple, isn't this?

Remember the unset() function that we saw above to remove the last element from an indexed array? It's actually meant to work with associative arrays, where we might want to remove any particular key.

In the code below, we remove the word count of 'as' from $word_counts:

<?php

$word_counts = [
   'as' => 10,
   'is' => 88,
   'us' => 16
];

// Storing the word count of 'as' isn't needed anymore.
unset($word_counts['as']);

echo 'Length: ', count($word_counts), "\n";
print_r($word_counts);
Length: 2 Array ( [is] => 88 [us] => 16 )

As it appears, the unset() call deletes the given key and modifies the length of the array.

unset() doesn't set a given key to NULL; rather, it actually deletes the underlying key (obviously including its value).

Moving on, two particularly useful functions used with associative arrays are array_keys() and array_values().

array_keys() extracts out all the keys from a given array while array_values() extracts out all the values. The return value of both these functions is yet another array (precisely speaking, an indexed array).

Shown below is an illustration:

<?php

$word_counts = [
   'as' => 10,
   'is' => 88,
   'us' => 16
];

print_r(array_keys($word_counts));
print_r(array_values($word_counts));
Array ( [0] => as [1] => is [2] => us ) Array ( [0] => 10 [1] => 88 [2] => 16 )

There is a huge inventory of functions related to associative arrays in PHP, which we shall explore in PHP Array Functions.

There's no reason why we couldn't call array_keys() or array_values() on an indexed array; it's just that there's no use of them.

We already know the keys so array_keys() is of no use. Similarly, array_values() would return the same array as the original indexed array, which is again of no use to us.

Array operators

Unlike many programming languages, PHP provides us with special (binary) operators to work with arrays. In this section, we'll take a look over these operators.

Basically there are just three operations to consider here: union, equality and identity. Inequality and non-identity are simply the negation of equality and identity, respectively, so there's nothing really special about them.

The array union (+) operator

The array union operator, denoted as +, as the name suggests, performs the union of two arrays.

That is, it takes two arrays and merges them together into a single new array with keys obtained from both the arrays. In case a particular key exists in both the given arrays, the one from the left-hand side array overrides the key in the right-hand side array.

Let's consider an example.

In the following code, we merge two indexed arrays, each holding three integers:

<?php

$evens = [0, 2, 4];
$odds = [1, 3, 5];

print_r($evens + $odds);
Array ( [0] => 0 [1] => 2 [2] => 4 )

The output clearly tells us that, because the keys 0, 1 and 2 occur in both the given arrays, the key-value pairs in the left-hand side array, which is $evens, take over in the final union array.

If we try adding some more integers to $odds, but hold on to $evens as it is right now, we'll be able to understand the union operation much better.

This is illustrated below:

<?php

$evens = [0, 2, 4];
$odds = [1, 3, 5, 7, 9];

print_r($evens + $odds);
Array ( [0] => 0 [1] => 2 [2] => 4 [3] => 7 [4] => 9 )

The addition of the elements 7 and 9 in the union array $evens + $odds here is reminiscent of the fact that merging is indeed happening.

Going back to the previous code snippet, let's say we wanted $odds to take over in the final union array. In that case, we'll do $odds + $evens, instead of $evens + $odds, as the left-hand side array dominates in the union operation:

<?php

$evens = [0, 2, 4];
$odds = [1, 3, 5];

// We want $odds to dominate if a particular key is duplicate.
print_r($odds + $evens);
Array ( [0] => 1 [1] => 3 [2] => 5 )

Moving on, it's apparent that unions can also be performed on associative arrays. Let's try doing so.

In the following code, we merge two associative arrays representing the counts of different words in the same piece of text:

<?php

$word_counts_1 = [
   'as' => 15,
   'is' => 31,
   'us' => 7,
];

$word_counts_2 = [
   'he' => 3,
   'she' => 10,
   'they' => 10,
];

print_r($word_counts_1 + $word_counts_2);
Array ( [as] => 15 [is] => 31 [us] => 7 [he] => 3 [she] => 10 [they] => 10 )

Wonderful!

The array equality (==) operator

The array equality operator, denoted as ==, serves to compare two arrays for equality based on whether they have the same key-value pairs (regardless of their order).

Just like == implements a loose equality check for other kinds of values in PHP, so does it for arrays.

If you recall arrays from JavaScript, this is different from how == behaves on arrays in JavaScript. That is, if two arrays have the exact same elements in the exact same order but their memory addresses are different, JavaScript doesn't consider them equal.

Shown below is a quick example:

<?php

$arr1 = [10, true, 'Hello World!'];
$arr2 = [10, true, 'Hello World!'];

var_dump($arr1 == $arr2);
bool(true)

Even though the arrays $arr1 and $arr2 are different from each other in terms of their memory location, they turn out to be equal and that's because PHP implements a customized array equality check.

But be wary of the fact that array equality checks, since they're loose and involve PHP's automatic type juggling, can produce unexpected results.

Here's an example:

<?php

$arr1 = [10, true, 'Hello World!'];
$arr2 = [true, 10, 'Hello World!'];

var_dump($arr1 == $arr2);

If you just read this code, you'll immediately assert that $arr1 is not equal to $arr2, and so $arr1 == $arr2 would yield false. Surprisingly, that's not the case!

bool(true)

The reason is pretty simple.

For each key in $arr1, a similar key is searched for in $arr2. If it's found, the values of both the keys are compared together using ==. If they're equal, we have a matching key-value pair.

In the code above, 10 is compared to true to determine if the first index is a match. Because PHP says that 10 == true is true, the first elements of $arr1 and $arr2 are equal. So is the case with the second element. And the third element is obviously equal as well.

For these reasons, it's always recommended to go for strict identity comparison, using ===. Fortunately, for us, we do have an array identity operator.

The array identity (===) operator

The array identity operator, denoted as ===, is used to determine whether two arrays are identical to one another.

Two arrays are considered identical if and only if they have the same key-value pairs (whereby the values are matched against each other using ===), in the exact same order.

Let's try this operator in the previous two code snippets above.

Here's the first snippet where we compare visually similar arrays:

<?php

$arr1 = [10, true, 'Hello World!'];
$arr2 = [10, true, 'Hello World!'];

var_dump($arr1 === $arr2);
bool(true)

And here's the second snippet where we compare visually different arrays:

<?php

$arr1 = [10, true, 'Hello World!'];
$arr2 = [true, 10, 'Hello World!'];

var_dump($arr1 === $arr2);
bool(false)

And there we have false; great!

As a rule of thumb, whenever comparing arrays, remember to use the array identity (===) operator.

Searching elements

Searching for elements in arrays is a routine activity that you'll inevitably want to do at some point in your coding journey. The good news is that doing so is really simple in PHP.

We can either use the in_array() or the array_search() function, depending on the nature of searching desired.

in_array()

The in_array() function checks whether a given value is 'in' an array or not.

Here's its syntax:

in_array($value, $array, $strict = false)

The first argument is the value to search for, while the second argument is the array to search in.

There's even a third optional argument, $strict, that specifies whether or not the searching should be strict, i.e. based on the comparison semantics of ===. By default, it's false which means that the comparisons are loose and done using the semantics of ==.

in_array() returns back a Boolean specifying whether the element exists in the array.

Let's take an example.

In the following code, we try to search for the city 'London' in $cities. Because 'London' indeed exists, the first in_array() call yields true, whereas since 'Paris' doesn't exist, the second call yields false.

<?php

$cities = ['Tokyo', 'London', 'Beijing', 'Karachi'];

var_dump(in_array('London', $cities));
var_dump(in_array('Paris', $cities));
bool(true) bool(false)

Demonstrating the loose searching behavior of in_array(), we have the following code:

<?php

$nums = [10, -5, 3];

var_dump(in_array(10, $nums));
var_dump(in_array(true, $nums));
bool(true) bool(true)

Even though true doesn't actually exist in $nums, in_array() somehow seems to find one. And that's by virtue of the fact that 10 == true is true in PHP.

Now, let's try making the comparisons here strict:

<?php

$nums = [10, -5, 3];

var_dump(in_array(10, $nums, true));
var_dump(in_array(true, $nums, true));
bool(true) bool(false)

And there you have it. The second in_array() call yields false this time. Voila!

array_search()

Do you recall the indexOf() method of arrays in JavaScript? Well, PHP's array_search() function works almost the same way.

array_search() searches for a given element in an array and returns back the index of its first occurrence, if there is any, or else false.

Here's its syntax:

array_search($value, $array, $strict = false)

As you can see, it's exactly the same as that of in_array() — first comes the value to search, then comes the array, and finally comes an optional argument to specify the kind of comparisons performed.

The return value of array_search() is either an integer or the Boolean false.

Let's consider some examples of using this function.

Below we have the same code as in the section above on in_array(), obviously with in_array() replaced with array_search():

<?php

$nums = [10, -5, 3];

var_dump(array_search(10, $nums));
var_dump(array_search(true, $nums));
int(0) int(0)

The second line of output here confirms that true is found at index 0, which means that true is indeed considered equal to 10.

As before, let's try using strict comparisons:

<?php

$nums = [10, -5, 3];

var_dump(array_search(10, $nums, true));
var_dump(array_search(true, $nums, true));
int(0) bool(false)

Once again, the second call yields false this time because true ain't identical to any integer.