Reputation: 11845
I am trying this code to check if a value exists in an array.
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (array_key_exists($num, $arr)) {
echo (array_key_exists($num, $arr)); //show the index, in this case 1
}
What i want is show the correspondent value, in other words, 0.58
How can i do that ?
Upvotes: 3
Views: 10511
Reputation: 10781
Assuming that you have the key or index position of the value you want, there are two functions that you could use, array_key_exists()
or isset()
.
array_key_exists()
checks an array to see if the key you specified exists within the array. It does not check to see if there is a value associated with this key. In other words the key may be set in the array, however the value could be null.
An example usage:
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (array_key_exists($num, $arr)) {
echo $arr[$num];
}
isset()
can be used to see if a value is set in a specific array index.
An example usage:
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (isset($arr[$num])) {
echo $arr[$num];
}
Since you seem to be asking to only check to see if a specific value exists within an array, you can take a look at using in_array()
which will scan the values of the array and return true or false depending on if it found the value.
An example usage:
$arr = array ('2' => '0', '3' => '0.58');
$needle = '0.58';
if (in_array($needle, $arr)) {
echo "found: $needle";
}
Additionally, php.net has a lot of other array functions that you should familiarize yourself with.
Upvotes: 2
Reputation: 1583
Try it
<?php
$arr = array(
'2' => '0',
'3' => '0.58'
);
$num = 3;
if (array_key_exists($num, $arr)) {
echo $arr[$num];
// 0.58
}
echo '<br/>';
$val = '0.58';
if (in_array($val, $arr)) {
echo '0.58 found';
}
?>
Upvotes: 1
Reputation: 4934
What you need is this:
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (array_key_exists($num, $arr)) {
echo $arr[$num];
}
Upvotes: 5