PHP比较数组键,而不是值 [英] php compare array keys, not values

查看:120
本文介绍了PHP比较数组键,而不是值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我成功地使用array_key_exists(),由php.net

I am successfully using the array_key_exists(), as described by php.net

例如:

<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
?>

不过,取出值,这是行不通的。

But, take out the values, and it doesn't work.

<?php
$search_array = array('first', 'second');
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
?>

不知道如何只通过唯一的按键比较2个阵列。

Not sure how to only compare 2 arrays by their keys only.

推荐答案

第一个例子是一个关联数组:使用指定的值的键。第二个例子是只是一个prettier的方式说:

The first example is an associative array: keys with values assigned. The second example is just a prettier way of saying:

array(0 => 'first', 1 => 'second')

对于第二个,你将需要使用 in_array 。你不应该检查一个密钥,该密钥 array_key_exists 做的presence,而是一个价值的presence其中 in_array 一样。

For the second, you would need to use in_array. You shouldn't check for the presence of a key, which array_key_exists does, but rather the presence of a value, which in_array does.

if(in_array('first', $array))

这篇关于PHP比较数组键,而不是值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆