Array operators are operators that are used on arrays. Who would have guessed? The first operator that we’ll look at is the + operator. You would think that this operator would be used to merge two arrays, taking elements from both arrays and merging them into a new array, but that is not the case.

If you were to output the result of the code above, you would quickly see that the result is:

The + operator creates a new array that combines key/value pairs. Elements with numeric keys 0, 1, and 2 exist in the first array, so they’re added to the $animals array; they are not overwritten by the second array. The second array does have an additional element at index 3, containing the value Puma, so that key/value pair is added to the new array $animals.

If you wanted to truly merge the two arrays together, containing the elements from both the first and second arrays, you will have to use the array_merge() built-in PHP function.

<?php

$fav_animals = array_merge($birds, $big_cats);
?>

This will create the result that you were most likely expecting. I’m going to be covering array_merge() in more detail later.

We can test the equality between two arrays using the equality operators: equal to (==), identical to (===), not equal to (!=), not identical to (!==).

We’ll start by creating two arrays: $car_1 and $car_2. Each of those arrays will contain key/value pairs with strings used for keys. The only difference between the values is that in $car_1, the year will be an integer value, and in $car_2, the year will be a string value. Everything else will remain the same.

Testing the values produces results similar to the ones when we compared strings. The equality operator tests to make sure that each key/value pair is the same. It does not test for the data type. The two arrays are equal in the eyes of PHP if we were to compare the two arrays using the == operator. Using the identity operator (===), the data types are tested as well. Even though both arrays store the value 2003, in the first array the value is an integer and in the second array the value is a string. PHP will see them as two different arrays.

#software-development #php #programming #computer-science #web-development #array

PHP 7.x — P21: Array Operators
1.25 GEEK