Home >Backend Development >PHP Problem >How to determine if a certain array exists in php
In PHP, we often need to operate on arrays. One common problem is how to determine whether an element exists in the array. PHP provides several methods to solve this problem, and this article will introduce the use of these methods.
1. Use the in_array() function
The in_array() function is a function in PHP used to determine whether an element exists in an array. This function accepts two parameters, the first parameter is the element to be checked, and the second parameter is the array to be checked. Returns TRUE if the element exists in the array, FALSE otherwise.
Sample code:
$fruit = array('apple', 'orange', 'banana'); if (in_array('apple', $fruit)) { echo '存在apple'; } else { echo '不存在apple'; }
Output result:
存在apple
2. Use array_search() function
array_search() function is also used to determine whether an element is A function that exists in an array. Unlike the in_array() function, the array_search() function returns the key name of the element in the array. If the element does not exist, it returns FALSE.
Sample code:
$fruit = array('apple', 'orange', 'banana'); $key = array_search('apple', $fruit); if ($key !== false) { echo '存在apple'; } else { echo '不存在apple'; }
Output result:
存在apple
3. Use isset() function
isset() function is used to check whether a variable has been Declared and the value is not NULL. We can use this function when checking if an array element exists.
Sample code:
$fruit = array('apple', 'orange', 'banana'); if (isset($fruit[0])) { echo '存在apple'; } else { echo '不存在apple'; }
Output result:
存在apple
4. Use array_key_exists() function
array_key_exists() function is used to determine whether a key name is exists in the array. Returns TRUE if the key exists, otherwise returns FALSE.
Sample code:
$fruit = array('apple', 'orange', 'banana'); if (array_key_exists(0, $fruit)) { echo '存在apple'; } else { echo '不存在apple'; }
Output result:
存在apple
Summary
The above are several ways to determine whether an element exists in an array in PHP. According to actual needs, we can choose a suitable method for judgment. It should be noted that when using the in_array() and array_search() functions, if you need to use strict equality comparison, you need to set the third parameter to TRUE.
The above is the detailed content of How to determine if a certain array exists in php. For more information, please follow other related articles on the PHP Chinese website!