Home  >  Article  >  Backend Development  >  How to detect whether array key exists in php

How to detect whether array key exists in php

青灯夜游
青灯夜游Original
2022-05-09 19:06:586268browse

Two methods: 1. Use "array_key_exists("specified key value", $arr)" and return true if it exists. 2. Use "isset($arr["specified key value"]" to check whether the value corresponding to the specified key name exists, and then determine whether the key exists. If it exists, it will return true.

How to detect whether array key exists in php

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

Two methods for PHP to detect whether the array key exists:

1. Use array_key_exists() function

array_key_exists() function checks whether the specified key name exists in an array and returns true if the key name exists. , if the key name does not exist, return false.

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr = array("Volvo" => "XC90", "BMW" => "X5");
if (array_key_exists("Volvo", $arr)) {
	echo "数组key存在!";
} else {
	echo "数组key不存在!";
}
?>

How to detect whether array key exists in php

2. Use the isset() function

isset() function Used to detect whether the variable has been set and is not NULL.

Detection idea:

  • Use array name["key"] to access the specified array element,

  • Use isset() function to detect whether the array element exists

    If it exists and is not NULL, return TRUE, otherwise return FALSE.

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr = array("Volvo" => "XC90", "BMW" => "X5");
if (isset($arr["a"])) {
	echo "数组key存在!";
} else {
	echo "数组key不存在!";
}
?>

How to detect whether array key exists in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to detect whether array key exists 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