Home Tutorial Php Phpbasics PHP Array Search Key

 
 

PHP Array Search Key
Posted on: October 27, 2009 at 12:00 AM
Advertisement
PHP Array Search Key: In this tutorial you will come to know that how to search a key of an array. array_key_exists() function helps us to search keys and returns a Boolean value. It does not work fine with multi-dimensional array, examples will illustrates these points.

PHP Array Search Key

To check a key of an array exists or not we use array_key_exists(). The function returns Boolean value that indicates that whether the given key exists within  the array or not. If the key exists in the array it returns True or the function returns false.

General description of array_key_exists() is: 

General Format boolean array_key_exists(mixed $key, array $array)
Parameters mixed $key: key to check

 

array $array: the array to be checked
Return Value Boolean value: True/False

 

PHP Array Search Key Example 1:

<?php

$array1=array("a"=>1,"b"=>2,"c"=>3);

echo"<br/><b>Initially the values of \$array1 is:</b><br/>";

var_dump($array1);

$key="c";

echo"<br/><b>The key is:$key</b><br/>";

if(array_key_exists($key,$array1))

echo"<br/><b>Found</b><br/>";

else

echo"<br/><b>Not Found</b><br/>";

?>

Output:

Initially the values of $array1 is:
array(3) {
  ["a"]=>
  int(1)
  ["b"]=>
  int(2)
  ["c"]=>
  int(3)
}

The key is:c

Found

Example 2:

<?php

$array1=array("b"=>array("x"=>"beneath","y"=>"benign"),"c"=>"contemporary","d"=>"diligent");

echo"<br/><b>Initially the values of \$array1 is:</b><br/>";

var_dump($array1);

$key="x";

echo"<br/><b>The key is:$key</b><br/>";

if(array_key_exists($key,$array1))

echo"<br/><b>Found</b><br/>";

else

echo"<br/><b>Not Found</b><br/>";

$key="c";

echo"<br/><b>New key is:$key</b><br/>";

if(array_key_exists($key,$array1))

echo"<br/><b>Found</b><br/>";

else

echo"<br/><b>Not Found</b><br/>";

?>

Output:

Initially the values of $array1 is:
array(3) {
  ["b"]=>
  array(2) {
    ["x"]=>
    string(7) "beneath"
    ["y"]=>
    string(6) "benign"
  }
  ["c"]=>
  string(12) "contemporary"
  ["d"]=>
  string(8) "diligent"
}

The key is:x

Not Found

New key is:c

Found

 

Advertisement

Related Tags for PHP Array Search Key:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 27, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com