Home >Backend Development >PHP Problem >How to determine whether an element exists in a php array
When using PHP arrays, sometimes you need to determine whether an element exists in the array. Below I will introduce several methods to determine the elements in a PHP array.
in_array($value, $array);
where $value is the value to be found, and $array is the target array. Its return value is a Boolean value. If the value to be found exists in the array, it returns true, otherwise it returns false. Here is an example:
$arr = array('apple', 'banana', 'orange'); if (in_array('apple', $arr)) { echo '数组中存在apple元素'; } else { echo '数组中不存在apple元素'; }
array_search($value, $array);
where $value is the value to be found, and $array is the target array. If the value to be found exists in the array, its key name is returned; otherwise, false is returned. The following is an example:
$arr = array('apple', 'banana', 'orange'); $key = array_search('banana', $arr); if ($key !== false) { echo '数组中存在banana元素,其键名为' . $key; } else { echo '数组中不存在banana元素'; }
isset($array[$key]);
Among them, $array is the target array, and $key is the key name to be judged. If the key name exists, it returns true, otherwise it returns false. The following is an example:
$arr = array('name' => 'Tom', 'age' => 18); if (isset($arr['name'])) { echo '数组中存在name键名'; } else { echo '数组中不存在name键名'; }
array_key_exists($key, $array);
Among them, $key is the key name to be judged, and $array is the target array. If the key name exists, it returns true, otherwise it returns false. The following is an example:
$arr = array('name' => 'Tom', 'age' => 18); if (array_key_exists('name', $arr)) { echo '数组中存在name键名'; } else { echo '数组中不存在name键名'; }
Summary
The above are several methods for judging elements in PHP arrays. In actual development, we can choose different methods to make judgments based on the actual situation.
The above is the detailed content of How to determine whether an element exists in a php array. For more information, please follow other related articles on the PHP Chinese website!