Detection steps: 1. Use array_filter() and is_string() to filter the array and return a filtered array containing all string elements. The syntax is "function f($v){return(array_filter($v)); }$res=array_filter($arr,"f");"; 2. Determine whether the filter array is an empty array, the syntax is "$res==[]", if it is an empty array, there is no string element, otherwise there is String element.
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In php, you can use array_filter() and is_string() function to detect whether a string element exists in an array.
Implementation steps:
Step 1: Use the array_filter() and is_string() functions to filter the array and return the characters in the array String elements
array_filter() function uses the callback function to filter the elements in the array and returns a filtered array. This function passes each key value in the input array to the callback function. If the callback function returns true, the current key value in the input array is returned to the result array. Array key names remain unchanged.
is_string() function is used to detect whether a variable is a string. Returns TRUE if the specified variable is a string, FALSE otherwise.
function f($v){ return(array_filter($v)); } $res=array_filter($arr,"f");
Step 2: Determine whether the filter array is an empty array
过滤数组==[]
If it is an empty array, it does not exist String element
If it is not an empty array, there is a string element
Implementation code:
function f($v){ return(is_string($v)); } function fun($arr){ var_dump($arr); $res=array_filter($arr,"f"); echo "过滤数组:"; var_dump($res); if($res==[]){ echo "数组中不存在字符串元素"; }else{ echo "数组中存在字符串元素"; } }
Call the fun() function above
$arr=array(2,4,"null",1,null,9); fun($arr);
$arr=array(2,4,1,null,9); fun($arr);
Recommended learning: "PHP Video Tutorial》
The above is the detailed content of How to detect whether there is a string element in an array in php. For more information, please follow other related articles on the PHP Chinese website!