Reputation: 122
This is my array in PHP:
$arr['key1']='value1';
$arr['key2']='value2';
$arr['key3']='value3';
$arr['key4']='value4';
$arr['key5']='value5';
$arr['key6']='value6';
I would like to test if a key is in the array. Is this function the correct way to proceed?
function isKeyInArray($key, $arr) {
if(isset($arr[$key]))
return true;
else
return false;
}
What I expect is that:
isKeyInArray('key3', $arr) // return true
isKeyInArray('key9', $arr) // return false
Many thanks in advance.
Upvotes: 0
Views: 186
Reputation: 49
Use php function array_key_exists('key3', $a);
First google your need and only after that you can use your own function. This will save lots of your time.
Upvotes: 0
Reputation: 2474
Using isset()
is good if you consider that null
is not a suitable value. Also isset
is faster than array_key_exists
.
$a = [ 'one' => 1, 'two' => null ];
isset($a['one']); // true
isset($a['two']); // false
array_key_exists('two', $a); // true
Upvotes: 2
Reputation: 23836
Use array_key_exists
if(array_key_exists('key6',$arr))
echo "present";
else
echo "not present";
Upvotes: 4
Reputation: 3741
You can use array_key_exists
.
$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (array_key_exists("Volvo",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
See http://php.net/manual/en/function.array-key-exists.php
Upvotes: 6