Home  >  Article  >  Backend Development  >  Can the key names of arrays in php be repeated?

Can the key names of arrays in php be repeated?

青灯夜游
青灯夜游Original
2022-04-29 14:05:281946browse

The key name of the php array cannot be repeated. In PHP, the key name of an array is unique and does not exist repeatedly. Even if two identical key names are declared, the key name declared later will overwrite the previous key name; using this feature, You can use array_flip() to reverse the key names and key values ​​of the array twice to achieve the array deduplication effect.

Can the key names of arrays in php be repeated?

The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer

The key name of the php array is not allowed repeat.

In PHP, the key name of the array is unique and will not exist repeatedly.

Example: There is such an empty array

$arr = array();//定义一个空数组
var_dump($arr);//输出数组

Can the key names of arrays in php be repeated?

Declaration of key-value pairs

//定义键值对元素
$arr["id"]=1;
$arr["name"]="李华";
$arr["age"]=20;
var_dump($arr);//输出数组

Can the key names of arrays in php be repeated?

Declaration Repeat the key name and assign the value

//声明重复键名,并赋值
$arr["id"]=10;
$arr["age"]=23;
var_dump($arr);//输出数组

Can the key names of arrays in php be repeated?

. It can be seen that even if two identical key names are declared, the key name declared later will overwrite the previous key name.

Extended knowledge: Using the non-repeatable feature of PHP array key names, you can remove duplicate values ​​from the array.

You only need to use the array_flip($array) function to reverse the key name and key value of the array twice:

  • First replace the key name and key value In order to remove duplicate values

  • and then swap the key name and key value back again

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr = array("a" => 1, "b" => 1, "c" => 2);
var_dump($arr);
$farr=array_flip($arr);
var_dump($farr);
var_dump(array_flip($farr));
?>

Can the key names of arrays in php be repeated?

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of Can the key names of arrays in php be repeated?. 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