Home > Article > Backend Development > How to check whether a specified element in an associative array exists in php
Checking method: 1. Use the in_array() function, the syntax is "in_array (specified element, array)", if it is included, it returns TRUE; 2. Use the array_search() function, the syntax is "array_search(value, array) ", if included, return the corresponding key name; 3. Use the foreach statement to loop through the array elements, and use the "$value===specified value" statement to determine whether the current array element is equal to the specified value. If equal, the array contains the value.
The operating environment of this tutorial: windows7 system, PHP8 version, DELL G3 computer
php queries whether the array exists A certain value
Method 1: Use the in_array() function
In php, if you want to query whether a certain value exists in the array, you can use it directly Built-in function in_array()
in_array() function searches the array for the presence of a specified value. Syntax format:
in_array ( $search , $array ,$strict)
Description | |
---|---|
search | Required. Specifies the value to search for in the array.|
array | Required. Specifies the array to search.|
strict | Optional. If this parameter is set to TRUE, the in_array() function checks whether the data being searched is of the same type as the value of the array.
<?php header('content-type:text/html;charset=utf-8'); $Array = array( 'Chandler' => 50, 'Monica' => 80, 'Ross' => 95 ); if (in_array("80", $Array)){ echo "存在指定值"; } else{ echo "不存在指定值"; } ?>
Method 2: Use array_search() function
The array_search() function searches for a key value in the array and returns the corresponding key name. You can also use this function to query whether a certain value exists in the array. If it exists, the corresponding key name will be returned. If it does not exist, it will return false. Syntax:array_search(value,array,strict)
Description | |
---|---|
value | Required. Specifies the key value to search for in the array.|
array | Required. Specifies the array to be searched.|
strict | Optional. If this parameter is set to TRUE, the function searches the array for elements of the same data type and value. Possible values:
|
<?php header('content-type:text/html;charset=utf-8'); $Array = array( 'Chandler' => 50, 'Monica' => 80, 'Ross' => 95 ); if (array_search("red", $Array)){ echo "存在指定值"; } else{ echo "不存在指定值"; } ?>
Method 3: Use foreach loop statement
<?php header('content-type:text/html;charset=utf-8'); $arr = array( 'Chandler' => 50, 'Monica' => 80, 'Ross' => 95 ); var_dump($arr); foreach($arr as $value){ if($value===50){ echo "包含指定值"; break; } } ?>
Recommended learning: "
PHP Video TutorialThe above is the detailed content of How to check whether a specified element in an associative array exists in php. For more information, please follow other related articles on the PHP Chinese website!