search
HomeBackend DevelopmentPHP TutorialPHP Master | Array Operators in PHP: Interesting but Less Spoken

Detailed explanation of PHP array operator: little-known tips

PHP Master | Array Operators in PHP: Interesting but Less Spoken

PHP operators can be divided into seven categories: arithmetic, assignment, bit operation, comparison, error control, execution, increment/decrease, logic, string, array and type operator. This article focuses on array operators and covers the behavior of some other operators when used in conjunction with arrays.

Key Points

  • PHP array operators include union, equality, identity, inequality, and non-identity. Each operator performs different functions, such as merging arrays, checking whether the array is equal or identifiable. and check if the array is not equal or non-identical.
  • The union operator ( ) merges two arrays according to the keys, ignoring the keys that already exist in the first array in the second array. However, it is often misunderstood that unions are based on array values, but in fact they are based on array keys.
  • Identity operator (===) checks whether the two arrays are the same in terms of the number of elements, key-value pairs, element order, and data types for all corresponding values. But for array keys, if the key is an integer, and there is a similar integer string representation as a key in another array, it will make a loose match.
  • PHP behaves differently when applying operators other than array operators to an array. For example, when applying an arithmetic operator to an array, PHP issues a fatal error; when using a logical operator, it treats an array as an integer; when using a string concatenation operator, it treats an array as a string. The increment/decrement operator has no effect on the array.

Array Operator

The official documentation only briefly describes each array operator, which sometimes makes it difficult for people to understand the expected results of each operator. Let's take a closer look at each array operator to get a clearer understanding of their functionality. All of these operators are binary, which means that each operator acts precisely on two arrays.

Array union

First is the union operator ( ), which gives the union of two arrays according to the keys of the array. It performs loose key matching, and if the equivalent key of the second array already exists in the first array, all keys of the second array are ignored. The remaining keys of the second array (and the corresponding values) are appended to the first array.

<?php
$array1 = array('a', 'b', 'c');
$array2 = array('d', 'e', 'f', 'g', 'h', 'i');
print_r($array1 + $array2);
print_r($array2 + $array1);
?>
<code>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
)</code>

For 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 result array. For the second print_r(), all keys of $array1 already exist in $array2, so all its elements are ignored. Loose matching behavior may give you totally unexpected results, but also provides 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);
?>
<code>Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => i
)</code>

People often misunderstand that unions are based on array values, but in fact this operator implements unions of array keys. For value-based union, you can use array_merge() and array_unique() in combination:

<?php
$array1 = array('a', 'b', 'c');
$array2 = array('d', 'e', 'f', 'g', 'h', 'i');
print_r($array1 + $array2);
print_r($array2 + $array1);
?>
<code>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
)</code>

Array equality

Equality operator (==) checks whether the two arrays are similar. If all key-value pairs in the first array have equivalent key-value pairs in the second array, the operator returns true. It loosely matches values ​​and keys and ignores the order of elements.

<?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);
?>
<code>Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => i
)</code>

The elements in both arrays are in different order, but the same values ​​are bound to similar keys in each array. However, the following two are not equal, because both arrays have different key-value pairs:

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

The unequal operator (!= or ) checks whether the two arrays are not similar and are perfect antonyms for the equal operator. The equality operator returns anything that false, 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);
?>
<code>bool(true)</code>

Array identity

Identity operator (===) checks whether the two arrays are the same. Two arrays are the same if they meet the following conditions:

  • Have the same number of elements
  • Has the same key-value pair
  • Have the same element order
  • The data type of all corresponding values ​​is the same

However, for array keys, if the key is an integer, and there is a similar integer string representation as a key in another array, the identity operator makes a loose match. This operator will strictly match the floating point number to the string key. The PHP manual does not state this difference.

<?php
$array1 = array(1, 2);
$array2 = array(2, 1);
var_dump($array1 == $array2);
?>
<code>bool(false)</code>
<?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);
?>
<code>bool(false)</code>
<?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);
?>
<code>bool(true)</code>

The non-identity operator (!==) checks whether the two arrays are different. Again, this operator is exactly the opposite of the identity operator, which means that if the two arrays are the same, this operator returns false.

<?php
// 两个数组中的元素顺序不同
$array1 = array('0' => '0', '1' => '1', '2' => '2', '3' => '3');
$array2 = array(1 => '1', 2 => '2', 3 => '3', 0 => '0');
var_dump($array1 === $array2);
?>
<code>bool(false)</code>

Use other operators and arrays

PHP behavior differs when applying operators other than the above operators to an array. Here is a list of these operators and how they behave when applied to an array.

Fatal error: Unexpected operand type

PHP will issue a fatal error when the following operator is applied to the array:

  • Bit operation non-operator (~)
  • Arithmetic Negative Operator (-)
  • Arithmetic subtraction operator (-)
  • Arithmetic multiplication operator (*)
  • Arithmetic division operator (/)

Treat arrays as integers

When used with the following operators, an array is treated as an integer. An empty array (no elements) is considered int(0), and a non-empty array is considered int(1).

  • Logical non-(!) returns true for empty arrays, and false when the operand array has one or more elements.
  • Bits and (&&)Return 1 if both operands are non-empty; if one or both operands are empty, return 0.
  • bit or (|) Returns 0 if both operands are empty; otherwise returns 1.
  • bit exclusive(^) Returns 0 if both arrays are empty or are non-empty. If one of the arrays is empty, return 1.
  • Use the left shift operator (
  • The right shift operator (>>) behaves similarly to the left shift, except that it moves to the right.
  • Module(%) Returns true if both arrays are non-empty. If the second array is empty, a "divided by zero" error is emitted. If the first array is empty, 0 (result of 0 % 1) is returned.
  • Logistic vs (&& and AND) Returns false if any array is empty. Return true if both arrays are non-empty.
  • Logical or (|| and OR) returns true if any operand array is non-empty. If both arrays are empty, false is returned.
  • If both arrays are empty or are non-empty, the logical XOR (XOR) returns false. Otherwise, if one of the arrays is empty, returns true.
  • Capt the array to bool, return false if the array is empty, otherwise return true.

Treat arrays as strings

When concatenating two arrays, the string concatenation operator (.) treats each array as a string "Array" and concatenates these strings.

<?php
$array1 = array('a', 'b', 'c');
$array2 = array('d', 'e', 'f', 'g', 'h', 'i');
print_r($array1 + $array2);
print_r($array2 + $array1);
?>
<code>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
)</code>

Invalid

Increment/decrement operators (and --) have no effect on the array.

<?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);
?>
<code>Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => i
)</code>

Conclusion

There is little actual documentation about PHP operators when used with arrays, but to learn more, you can view user-submitted comments on the Array Operators page. Your questions and comments are welcome here and I will be happy to explain further.

Pictures from Fotolia

PHP Array Operator FAQs (FAQs)

What are the different types of array operators in PHP?

PHP supports several types of array operators, including union ( ), equality (==), identity (===), inequality (!= or ) and non-constant Equality (!==). Each of these operators performs a different function. For example, the union operator ( ) combines an array, the equality operator (==) checks whether the two arrays are equal, and the identity operator (===) checks whether the two arrays are the same.

How does the union ( ) operator work in PHP?

The union ( ) operator in PHP combines two numbers into one. It takes a union of arrays, which means it returns an array containing all elements in two arrays. If the array has the same string key, the value from the first array will be used, and the value of the matching key in the second array will be ignored.

What is the difference between equality (==) and identity (===) operators?

The

Equality (==) operator checks whether two arrays have the same key/value pairs, regardless of their order or data type. On the other hand, the identity (===) operator checks whether two arrays have the same key/value pairs of the same order and the same data type.

How does the inequality (!= or ) operator in PHP work?

The unequal operator in PHP is represented by != or to check whether the two arrays are not equal. Return true if the array is not equal, and false if the array is equal.

What is the role of the non-identity (!==) operator in PHP?

The non-identity (!==) operator in PHP checks whether the two arrays are different. Return true if the array is not the same; false if the array is the same.

Can array operators be combined in PHP?

Yes, you can combine array operators in PHP to perform more complex operations. However, be careful when doing this to avoid unexpected results. Always ensure that the combined operators have logical significance in the context of the code.

How to check if an array contains a specific value using the array operator?

You can use the in_array() function in PHP to check if an array contains a specific value. If the value is found in the array, this function returns true; otherwise, it returns false.

How to delete a specific value from a PHP array?

You can use the array_diff() function in PHP to delete a specific value from an array. This function compares the values ​​in the array with the values ​​in another array and returns the difference.

How to sort arrays in PHP?

PHP provides multiple functions to sort arrays, including sort(), asort(), ksort(), and usort(). Each of these functions sorts the array in a different way, so you should choose the one that best suits your needs.

How to reverse the order of arrays in PHP?

You can use the array_reverse() function in PHP to invert the order of the array. This function returns a new array of elements in reverse order.

The above is the detailed content of PHP Master | Array Operators in PHP: Interesting but Less Spoken. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

How to implement array sliding window in PHP?How to implement array sliding window in PHP?May 15, 2025 pm 08:51 PM

Implementing an array sliding window in PHP can be done by functions slideWindow and slideWindowAverage. 1. Use the slideWindow function to split an array into a fixed-size subarray. 2. Use the slideWindowAverage function to calculate the average value in each window. 3. For real-time data streams, asynchronous processing and outlier detection can be used using ReactPHP.

How to use the __clone method in PHP?How to use the __clone method in PHP?May 15, 2025 pm 08:48 PM

The __clone method in PHP is used to perform custom operations when object cloning. When cloning an object using the clone keyword, if the object has a __clone method, the method will be automatically called, allowing customized processing during the cloning process, such as resetting the reference type attribute to ensure the independence of the cloned object.

How to use goto statements in PHP?How to use goto statements in PHP?May 15, 2025 pm 08:45 PM

In PHP, goto statements are used to unconditionally jump to specific tags in the program. 1) It can simplify the processing of complex nested loops or conditional statements, but 2) Using goto may make the code difficult to understand and maintain, and 3) It is recommended to give priority to the use of structured control statements. Overall, goto should be used with caution and best practices are followed to ensure the readability and maintainability of the code.

How to implement data statistics in PHP?How to implement data statistics in PHP?May 15, 2025 pm 08:42 PM

In PHP, data statistics can be achieved by using built-in functions, custom functions, and third-party libraries. 1) Use built-in functions such as array_sum() and count() to perform basic statistics. 2) Write custom functions to calculate complex statistics such as medians. 3) Use the PHP-ML library to perform advanced statistical analysis. Through these methods, data statistics can be performed efficiently.

How to use anonymous functions in PHP?How to use anonymous functions in PHP?May 15, 2025 pm 08:39 PM

Yes, anonymous functions in PHP refer to functions without names. They can be passed as parameters to other functions and as return values ​​of functions, making the code more flexible and efficient. When using anonymous functions, you need to pay attention to scope and performance issues.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft