Home >Backend Development >PHP Problem >How to determine whether an element is in an array in php
Method: 1. Use the in_array() function to detect whether there is a specified element value in the array, the syntax is "in_array(element value, array)"; 2. Use the array_search() function to search in the array Specify element value, syntax "array_search(element value, array)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
# judge one in php Is the element in the array?
Method 1: Use the in_array() function
The in_array() function can find whether the array contains an Value, returns TRUE if it exists, FALSE if it does not exist. The syntax format is as follows:
in_array($needle, $array[, $strict = FALSE])
The parameter description is as follows:
Tip: The in_array() function is only suitable for finding an element in a one-dimensional array, and will not recursively search for elements in each dimension of the array.
Example: Use the in_array() function to determine whether the array contains a certain value
<?php header("Content-type:text/html;charset=utf-8"); $sites = array('a', 'b', '1', 2, 3); if (in_array("a", $sites)) { echo "指定元素在数组中"; } else { echo "指定元素不在数组中"; } ?>
2. Use the array_search() function
array_search() function searches for a key value in the array and returns the corresponding key name.
If the specified key value is found in the array, return the corresponding key name, otherwise return FALSE. If a key value is found more than once in the array, the key name matching the first found key value is returned.
The syntax format of this function is as follows:
array_search($needle, $haystack[, $strict = false])
The parameter description is as follows:
<?php header("Content-type:text/html;charset=utf-8"); $sites = array("a"=>"red","b"=>"green","c"=>"blue"); if (array_search("red",$sites)) { echo "指定元素在数组中"; } else { echo "指定元素不在数组中"; } echo "<br>指定元素的键名为:".array_search("red",$sites); ?> ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to determine whether an element is in an array in php. For more information, please follow other related articles on the PHP Chinese website!