Array Operators in PHP: Interesting but Less Spoken

    Hamid Sarfraz
    Share

    Operators in PHP can be organized into seven different categories: arithmetic, assignment, bitwise, comparison, error control, execution, incrementing/decrementing, logical, string, array, and type operators. This article details working with array operators, but also covers how some of the other operators work when used with arrays.

    Array Operators

    The official documentation provides just a quick description of each of the array operators, which sometimes can make it ambiguous as to what to expect from which each operator. Let’s take a look at each of the array operators for a much clearer understanding of what they do. All these operators are binary, that is each operates on exactly two arrays.

    Array Union

    First is the union operator (+) which gives the union of two arrays based on the arrays’ keys. It does loose key matching and all keys of the second array are ignored if their equivalent key already exists in the first array. The rest of the keys (and the corresponding values) of the second array are appended to the first.

    <?php
    $array1 = array('a', 'b', 'c');
    $array2 = array('d', 'e', 'f', 'g', 'h', 'i');
    print_r($array1 + $array2);
    print_r($array2 + $array1);
    Array
    (
        [0] => a
        [1] => b
        [2] => c
        [3] => g
        [4] => h
        [5] => i
    )
    Array
    (
        [0] => d
        [1] => e
        [2] => f
        [3] => g
        [4] => h
        [5] => i
    )

    With the first print_r(), the first three elements in $array2 have keys that already exist in $array1, so ‘d’, ‘e’, and ‘f’ are ignored in the resulting array. With the second print_r(), all of the keys of $array1 already exist in array $array2 so all of its elements are ignored.

    The loose matching behavior may give you totally unexpected results, but also opens up exciting opportunities for optimization and loose coding.

    <?php
    $array1 = array('0' => 'a', '1' => 'b', '2' => 'c', '3' => 'd');
    $array2 = array(false => 'e', 1 => 'f', 2 => 'g', 3 => 'h', 4 => 'i');
    print_r($array1 + $array2);
    Array
    (
        [0] => a
        [1] => b
        [2] => c
        [3] => d
        [4] => i
    )

    It is often misunderstood that the union is based on the array values, while in reality this operator implements the union of array keys. For value-based union, you can use a combination of array_merge() and array_unique():

    <?php
    $union = array_unique(array_merge($array1, $array2));
    print_r($union);
    Array
    (
        [0] => a
        [1] => b
        [2] => c
        [3] => d
        [4] => e
        [5] => f
        [6] => g
        [7] => h
        [8] => i
    )

    Array Equality

    The equality operator (==) checks whether two arrays are similar. The operator returns true if all key-value pairs in first array have equivalent key-value pairs in the second array. It matches values and keys loosely and the sequence of elements is ignored.

    <?php
    $array1 = array('1' => 1, '2' => 2, '3' => 3, '0' => 0);
    $array2 = array(false => '0', 1 => '1', 2 => '2', 3 => '3');
    var_dump($array1 == $array2);
    bool(true)

    The sequence of elements in the two arrays is different, but the same values are tied to similar keys in each array. However, the following are not equivalent because both arrays have different key value pairs:

    <?php
    $array1 = array(1, 2);
    $array2 = array(2, 1);
    var_dump($array1 == $array2);
    bool(false)

    The inequality operator (!= or <>) checks whether two arrays are not similar, and is a perfect opposite of the equality operator. Anything that the equality operator returns false for, this operator returns true, and vice versa.

    <?php
    $array1 = array('1' => 1, '2' => 2, '3' => 3, '0' => 0);
    $array2 = array(false => '0', 1 => '1', 2 => '2', 3 => '3');
    var_dump($array1 != $array2);
    bool(false)

    Array Identity

    The identity operator (===) checks if two arrays are identical. The arrays are identical if both arrays:

    • have the same number of elements
    • have the same key-value pairs
    • have the same sequence of elements
    • have the same data type of all corresponding values

    However, for array keys, the identity operator matches loosely if a key is an integer and a similar string notation of the integer exists as a key in the other array. For a float vs. string key match, this operator goes strict. The PHP manual does not clarify this difference.

    <?php
    // arrays are almost identical but keys have different types
    $array1 = array('0' => '0', '1' => '1', '2' => '2', '3' => '3');
    $array2 = array(0 => '0', 1 => '1', 2 => '2', 3 => '3');
    var_dump($array1 === $array2);
    bool(true)
    <?php
    // the sequence of elements in both arrays is not the same
    $array1 = array('0' => '0', '1' => '1', '2' => '2', '3' => '3');
    $array2 = array(1 => '1', 2 => '2', 3 => '3', 0 => '0');
    var_dump($array1 === $array2);
    bool(false)
    <?php
    // the key in the first array is a string and in the second is a float
    $array1 = array('0.5' => '0');
    $array2 = array(0.5 => '0');
    var_dump($array1 === $array2);
    bool(false)

    The non-identity operator (!==) checks if two arrays are not identical. Again, this operator is the exact opposite of the identity operator, which means this operator returns false for a comparison of arrays if they are identical.

    <?php
    $array1 = array('0' => '0', '1' => '1', '2' => '2', '3' => '3');
    $array2 = array(0 => '0', 1 => '1', 2 => '2', 3 => '3');
    var_dump($array1 !== $array2);
    bool(false)

    Using Arrays with Other Operators

    PHP behaves differently when operators other than those mentioned above are applied to arrays. Here is a list of those operators and the behavior when they are applied to arrays.

    Fatal Error: Unexpected Operand Type

    PHP issues a fatal error when the following operators are applied to arrays:

    • bitwise-not operator (~)
    • arithmetic negation Operator (-)
    • arithmetic subtraction operator (-)
    • arithmetic multiplication operator (*)
    • arithmetic division operator (/)

    Arrays Treated as Integers

    Arrays are treated as integers when used with the following operators. An empty array (with no elements) is considered as int(0) and non-empty arrays are considered int(1).

    • Logical-not (!) returns true for an empty array and false when the operand array has one or more elements.
    • Bitwise-and (&) returns 1 if both of its operands are non-empty and 0 if one or both of its operands are empty.
    • Bitwise-or (|) returns 0 if both of its operands are empty, otherwise it returns 1.
    • Bitwise-xor (^) returns 0 if both arrays are either empty or filled. If one of the arrays is empty, it returns 1.
    • Shifting an array n-steps to the left with the left-shit operator (<<) returns the integer equivalent of 1 << n if the array is non-empty. Otherwise it returns 0 (the outcome of 0 << n).
    • The right-shift operator (>>) has similar behavior as left-shift except that it shifts rightward.
    • Modulus (%) returns true if both of the arrays are non-empty. If the second array is empty, it issues a “Division by Zero” error. If the first array is empty, it returns 0 (the result of 0 % 1).
    • Logical-and (&& and AND) return false if any of the arrays are empty. If both arrays are non empty, it returns true.
    • Logical-or (|| and OR) return true if any of the operand arrays are non-empty. If both arrays are empty, it returns false.
    • If both of the arrays are either empty or non empty, logical-xor (XOR) returns false. Otherwise, it returns true if one of the arrays is empty.
    • Casting an array to bool gives false if the array is empty, otherwise true.

    Arrays Treated as Strings

    When concatenating two arrays, the string concatenation operator (.) takes each array as the string “Array” and concatenates these strings.

    <?php
    $array1 = array(0, 1, 2, 3);
    $array1 = array(0, 1, 2, 3);
    var_dump($array1 . $array2);
    string(10) "ArrayArray"

    No Effect

    The incrementing/decrementing category of operators (++ and --) have no impact on arrays.

    <?php
    $array1 = $array2;
    var_dump((++$array1) === $array2);
    bool(true)

    Conclusion

    The actual documentation on how PHP’s operators behave when used with arrays is sparse, but for more information you can look at the user submitted comments in the array operators page. Your questions and comments are welcome here too, and I shall happily explain things further.

    Image via Fotolia