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

31次阅读
没有评论

共计 580 个字符,预计需要花费 2 分钟才能阅读完成。

要检查一个键是否存在于数组中,可以使用 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() 函数。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-04-09发表,共计580字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)