php To search array strings, we generally use the two functions array_search and in_array
array_search()
函数与in_array()
to find a key value in the array. If the value is found, the key of the matching element is returned. If not found, returns false.
But array_search is generally used to search for the first string that meets the requirements in an array. If the searched string contains multiple strings in the array, array_search will not work. At this time, we use the array_keys() function to realize that the searched string contains multiple strings in the array.
Look at the following example:
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red'); $a=array_search( "blue",$array); //将输出$a=0; $b=array_search( 'red',$array); //将只会输出$b=1; $p = array_keys($array, 'red');//搜索的字符串在数组中含有多个 if(is_array($p)) { foreach($p as $v) { echo $val."出现在".$v . " "; } }else { echo $val."出现在".array_search($val, $array)." "; }
Example 2:
$array = array(4,5,7,8,9,10); $found = array_search(8, $array); //调用array_search函数并输出查找结果 if($found){ //如果找到输出键 echo "已找到,键为".$found; }else{ //如果没有找到输出错误信息 echo "没有找到"; }
Let’s take a look at the in_array function
Use in_array(value,array,type)
type is optional. If this parameter is set to true, it is checked whether the type of the searched data and the value of the array are the same.
$arr = array('可以','如何','方法','知道','沒有','不要'); //in_array(value,array,type) $isin = in_array("如何2",$arr); if($isin){ echo "in====".$isin; }else{ echo "out====".$isin; }
That’s all the content of this article, I hope you all like it
The above introduces the PHP array string search array_search technique, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.