Home  >  Article  >  Backend Development  >  How to determine whether an element exists in a php array

How to determine whether an element exists in a php array

PHPz
PHPzOriginal
2023-04-27 09:04:37534browse

In PHP programming, it is often necessary to operate on data, and arrays are one of the commonly used ways to store data. When using an array, you often need to determine whether an element exists. This article will introduce how to determine whether an element in an array exists in PHP.

In PHP, two functions are provided that can be used to determine whether an element in an array exists: in_array() and array_key_exists().

1. in_array() function

The in_array() function is used to find a given value in the specified array. If the value is found, it returns true, otherwise it returns false. The syntax of this function is as follows:

in_array($value, $array, $strict);

Among them, $value represents the value to be found, $array represents the array to be found, and $strict Indicates whether to use strict mode for search. When $strict is set to true, not only numeric types are matched, but also data types.

Sample code:

<?php
// 定义一个数组
$arr = array("apple", "banana", "orange");

if (in_array("apple", $arr)) {
    echo "apple 存在于数组中";
} else {
    echo "apple 不存在于数组中";
}
?>

The output result is:

apple 存在于数组中

2. array_key_exists() function

array_key_exists() function is used to determine the specified key name Whether it exists in the array, if it exists, it returns true, otherwise it returns false. The syntax of this function is as follows:

array_key_exists($key, $array);

Among them, $key represents the key name to be searched, and $array represents the array to be searched.

Sample code:

<?php
// 定义一个数组
$arr = array("name" => "Tom", "age" => 18, "gender" => "male");

if (array_key_exists("age", $arr)) {
    echo "age 存在于数组中,值为:" . $arr["age"];
} else {
    echo "age 不存在于数组中";
}
?>

The output result is:

age 存在于数组中,值为:18

Summary

To determine whether an array element exists in PHP, you can use the in_array() function or array_key_exists() function. The in_array() function is used to determine whether the specified element value exists in the array, and the array_key_exists() function is used to determine whether the specified key name exists in the array. It should be noted that when using the in_array() function, if there is an element with a value of false in the array, the function will return false, so it needs to be used with caution.

The above is the detailed content of How to determine whether an element exists in a php 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