How to determine whether it is an associative array or an index array in php

青灯夜游
Release: 2023-03-15 16:24:01
Original
3294 people have browsed it

Judgment method: 1. Use array_values() to convert the specified array into an index array; 2. Use array_diff_key() to compare the key names of the original array and the index array, and return a difference array; 3. Use empty() ) determines whether the difference array is an empty array. If so, the original array is an index array, otherwise it is an associative array.

How to determine whether it is an associative array or an index array in php

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

php determines whether it is related Array or index array method:

Implementation idea:

  • Use the array_values() function to obtain all key values ​​​​of the specified array and convert them For the index array

  • Use the array_diff_key() function to compare the key names of the converted index array and the original array, and return the difference array

  • Use empty () Determine whether the difference array is an empty array. If the difference array is an empty array, the original array is an index array, otherwise it is an associative array.

Implementation code:

<?php
header("Content-type:text/html;charset=utf-8");
function f($arr){
	$value=array_values($arr);
	$result=array_diff_key($arr,$value);
	var_dump($result);
	if (empty($result)){
		echo "原数组为索引数组";
	}
	else{
		echo "原数组为关联数组";
	}
}
$arr1=array("a"=>"red","b"=>"green","c"=>"blue");
f($arr1);
$arr2=array(1,2,3,4,5);
f($arr2);
?>
Copy after login

How to determine whether it is an associative array or an index array in php

Description:

array_values() function can Get the values ​​of all elements in the array; this function is particularly suitable for arrays with confusing element subscripts, or for converting associative arrays into indexed arrays.

array_diff_key() function is used to compare the key names of two (or more) arrays and return the difference array.

If the difference array is an empty array, the key names of the two (or more) arrays are the same.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to determine whether it is an associative array or an index 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