PHP怎么检查一个键或值是否存在于数组中

2024-04-02

要检查一个键是否存在于数组中,可以使用array_key_exists()函数。示例代码如下:

$array = ['a' => 1, 'b' => 2, 'c' => 3];

if (array_key_exists('a', $array)) {
    echo 'The key "a" exists in the array.';
} else {
    echo 'The key "a" does not exist in the array.';
}

要检查一个值是否存在于数组中,可以使用in_array()函数。示例代码如下:

$array = ['a', 'b', 'c'];

if (in_array('a', $array)) {
    echo 'The value "a" exists in the array.';
} else {
    echo 'The value "a" does not exist in the array.';
}

另外,你也可以使用array_key_exists()函数来检查一个值是否存在于数组中,但是这样会比较慢。因此,如果只需要检查值是否存在,推荐使用in_array()函数。

《PHP怎么检查一个键或值是否存在于数组中.doc》

下载本文的Word格式文档,以方便收藏与打印。