Home  >  Article  >  Backend Development  >  How to detect whether there is a string element in an array in php

How to detect whether there is a string element in an array in php

青灯夜游
青灯夜游Original
2022-09-21 20:16:061796browse

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.

How to detect whether there is a string element in an array in php

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);

How to detect whether there is a string element in an array in php

$arr=array(2,4,1,null,9);
fun($arr);

How to detect whether there is a string element in an array in php

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn