Home >Backend Development >PHP Problem >How does PHP determine whether a certain key or index exists in an array?

How does PHP determine whether a certain key or index exists in an array?

青灯夜游
青灯夜游Original
2019-10-15 14:36:135556browse

In PHP, you can use the built-in function array_key_exists() to determine whether a key or index exists in the array. The following article will introduce you to the PHP array_key_exists() function. I hope it will be helpful to you.

How does PHP determine whether a certain key or index exists in an array?

array_key_exists()

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

Tip: Please remember that if you omit the key name when specifying the array, integer key names will be generated starting from 0 and increasing by 1.

Syntax:

array_key_exists(key,array)

Parameters:

  • key: required, given key name or index, which can be any value that can be used as an array index.

  • array: required, specifies the array.

Example 1: Check whether the key name "Toyota" exists in the array:

<?php
header("content-type:text/html;charset=utf-8");
$a = array("Volvo" => "XC90", "BMW" => "X5");
if (key_exists("Toyota", $a)) {
	echo "Key存在!";
} else {
	echo "Key不存在!";
}
?>

Output:

Key不存在!

Example 2: Check whether the integer key name "0" exists in the array:

<?php
header("content-type:text/html;charset=utf-8");
$a = array("Volvo", "BMW");
if (array_key_exists(0, $a)) {
	echo "Key存在!";
} else {
	echo "Key不存在!";
}
?>

Output:

Key存在!

For more PHP related knowledge, please Visit PHP Chinese website!

The above is the detailed content of How does PHP determine whether a certain key or index exists in an array?. 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