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

青灯夜游
Release: 2023-02-26 18:30:01
Original
5488 people have browsed it

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)
Copy after login

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不存在!";
}
?>
Copy after login

Output:

Key不存在!
Copy after login

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不存在!";
}
?>
Copy after login

Output:

Key存在!
Copy after login

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!

Related labels:
php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!