How Do You If a Key Is Defined in an Array

Q

How Do You If a Key Is Defined in an Array? - PHP Script Tips - PHP Built-in Functions for Arrays

✍: FYIcenter.com

A

There are two functions can be used to test if a key is defined in an array or not:

  • array_key_exists($key, $array) - Returns true if the $key is defined in $array.
  • isset($array[$key]) - Returns true if the $key is defined in $array.

Here is a PHP example script:

<?php 
$array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
print("Is 'One' defined? ".array_key_exists("One", $array)."\n");
print("Is '1' defined? ".array_key_exists("1", $array)."\n");
print("Is 'Two' defined? ".isset($array["Two"])."\n");
print("Is '2' defined? ".isset($array[2])."\n");
?>

This script will print:

Is 'One' defined? 1
Is '1' defined?
Is 'Two' defined? 1
Is '2' defined?

2007-04-20, 4818👍, 0💬