check if a value exists in array

10.2k Views Asked by At

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 ?

4

There are 4 best solutions below

0
On BEST ANSWER

What you need is this:

$arr = array ('2' => '0', '3' => '0.58');

$num=3;
if (array_key_exists($num, $arr)) {
    echo $arr[$num];
}
0
On
var_dump(in_array(0.58, $arr)); // 3

relevant docs.

1
On

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';
}
?>
0
On

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.