3

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 ?

daniel__
  • 11,633
  • 15
  • 64
  • 91
  • 1
    You mean `$arr['3']`? Where are you getting `$numCol` and `$IA` from? – animuson Nov 21 '11 at 02:17
  • The index of the key `3` is not `1`, it's `3`. It's the *second* entry in the array, but this information is not necessarily retrievable. – deceze Nov 21 '11 at 02:22
  • sorry, I changed the names of the variables when I copied, and i forgot these ones. – daniel__ Nov 21 '11 at 02:23

4 Answers4

5

What you need is this:

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

$num=3;
if (array_key_exists($num, $arr)) {
    echo $arr[$num];
}
Alex
  • 4,844
  • 7
  • 44
  • 58
2

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.

hafichuk
  • 10,351
  • 10
  • 38
  • 53
1
var_dump(in_array(0.58, $arr)); // 3

relevant docs.

Marc B
  • 356,200
  • 43
  • 426
  • 500
1

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';
}
?>
alexdets
  • 1,473
  • 1
  • 8
  • 3
  • Note that unless you expect NULL values `isset($arr[$num])` is equivalent but lot faster to `array_key_exists`. – chx Nov 21 '11 at 04:29