How to determine whether it is an associative array in php

青灯夜游
Release: 2023-03-16 07:42:02
Original
2359 people have browsed it

Judgment steps: 1. Use array_keys() to get all the key names of the array. The syntax "array_keys($arr)" will return a key array containing all key names; 2. Use foreach to traverse the key names. Array, in the loop body, determine whether any array element is of string type. As long as one is, it is an associative array. The syntax "foreach($k as $v){if(is_string($v)){echo "is associative Array ";}}".

How to determine whether it is an associative array in php

The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer

What is an associative array

The subscript (key name) of an associative array is composed of a mixture of numeric values ​​and strings. If a key name in an array is not a number, then the array is an associative array.

How does PHP determine whether it is an associative array

1. Use array_keys() to get the key name of the array

array_key() function can get some or all key names in the array and return an array of key names

<?php
header("Content-type:text/html;charset=utf-8");
$arr=array(1=>"1","a"=>"red",2=>"2","b"=>"green","c"=>"blue");
var_dump($arr);
$keys=array_keys($arr);
var_dump($keys);
?>
Copy after login

How to determine whether it is an associative array in php

2. Use foreach to traverse the key names Array

In the loop body, determine whether any array element is a string

  • As long as one of the array elements is a string, the array is an associative array

foreach($keys as $v){
	if(is_string($v)){
		echo "是关联数组";
		break;
	}
}
Copy after login

How to determine whether it is an associative array in php

Improve it: Determine whether the array is an associative array or an index array

$keys=array_keys($arr);
$b="";
foreach($keys as $v){
	if(!is_string($v)){
		$b=false;
	}else{
		$b=true;
		break;
	}
}
if($b){
	echo "是关联数组";
}else{
	echo "不是关联数组,是索引数组";
}
Copy after login

If the detection is The following array:

$arr=array(1,2,3,4,5);
Copy after login

will output:

How to determine whether it is an associative array in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to determine whether it is an associative array in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template