How to Check if an Array Index Exists in PHP
PHP has many procedures that simplify working with arrays. Arrays in PHP are ordered maps or structures that associate keys with values. Ordered maps are optimized as arrays, hash tables, dictionaries, collections, stacks and queues. There are three basic array types in PHP: numeric arrays (numeric indexes), associative arrays (indexes that have ID keys associated with values), and multidimensional arrays (arrays that contain other arrays). PHP also offers a variety of array functions that allow developers to check array values, alter arrays and verify the existence of array indexes and values.
- Difficulty:
- Easy
Instructions
Things You'll Need
- text editor
- Web browser
- PHP installed and properly configured on a Web server
-
-
1
Open a text editor and create a new file named findElement.php The typical steps for creating a new file in a text editor is to select “New” from the “File” menu.
-
2
Add an open PHP delimiter (“<?php”) and a close PHP delimiter (“?>”) to findElement.php. These delimiters tell that PHP interpreter that any text placed between them is PHP code.
<?php
?> -
3
Create an array named “$check_array” using the PHP “array” function and place the array between the open and close PHP delimiters. The $check_array array should have three items with the following keys (indexes) and values: “first”; “1”, “second”; “2” and “third”; ‘3’.
$search_array = array('first' => 1, 'second' => 4, 'third' => 5);
-
4
Add an “if” conditional statement to findElement.php following the $search_array array declaration. The conditional uses the “array_key_exists” method to determine whether or not the key “third” exists in the $search_array array. Use two curly braces (“{}”) to hold the place for the code that will execute if the condition is true (the array key "third" exists).
if (array_key_exists('third', $search_array)) {}
-
5
Use a PHP “echo” construct to print the response “The ‘third’ element exists” to the Web page if the “third” array key exists in the array. Place the command between the conditional statements curly braces. After step five findElement.php will appear as shown below:
<?php
$search_array = array('first' => 1, 'second' => 4, 'third' => 5);
if (array_key_exists('third', $search_array)) {
echo "The 'third' element exists";
}
?> -
6
Open findElement.php in a Web browser. Verify that the element with the index “third” is found and the correct response prints to the Web page ("The 'third' element exists").
-
1
Tips & Warnings
Array indexes (keys) in PHP may be either numeric or string types. Keys may also be associated with values.
Array values can be used to search PHP arrays using the “in_array()” function.
There are dozens of PHP array functions that can be used to sort, reorder, remove and add items to arrays.
Remember that PHP numbered indexes start with “0” rather than “1”.
Related Searches
References
Resources
- Photo Credit Dynamic Graphics/Dynamic Graphics Group/Getty Images