Using array_key_exists() to Check for Keys in PHP Arrays
This article explains how to use PHP's built-in array_key_exists() function to determine whether a specified key exists in associative arrays, indexed arrays, or object properties, providing syntax details and practical code examples for both associative and indexed arrays.
In PHP, arrays are fundamental data structures that can store values of any type and are accessed via keys. When you need to verify whether a particular key is present in an array, PHP provides a convenient built‑in function.
The function array_key_exists() checks if a given key exists in an array and returns a boolean value: true if the key is found, otherwise false . Its basic syntax is:
<code>bool array_key_exists ( mixed $key , array $array )</code>Below is a concrete example demonstrating the use of array_key_exists() with an associative array.
<code><?php<br/>// Define an associative array<br/>$arr = array(<br/> 'name' => '张三',<br/> 'age' => 18,<br/> 'address' => '北京市朝阳区'<br/>);<br/><br/>// Check whether the key 'age' exists<br/>if (array_key_exists('age', $arr)) {<br/> echo '该数组中存在age键名。';<br/>} else {<br/> echo '该数组中不存在age键名。';<br/>}<br/>?></code>In this example, the associative array $arr contains the key 'age' , so the function returns true and the script outputs “该数组中存在age键名。”.
The same function can also be applied to indexed (numeric) arrays. The following example checks for the existence of an index:
<code><?php<br/>// Define an indexed array<br/>$arr = array(1, 2, 3, 4, 5);<br/><br/>// Check whether the index 2 exists<br/>if (array_key_exists(2, $arr)) {<br/> echo '该数组中存在下标为2的元素。';<br/>} else {<br/> echo '该数组中不存在下标为2的元素。';<br/>}<br/>?></code>Here the array indeed has an element at index 2 , so the function returns true and the script prints “该数组中存在下标为2的元素。”.
Summary The array_key_exists() function can be used to check whether a specific key or index exists in an array or an object property. It works with associative arrays, indexed arrays, and objects, making key existence checks simple and reliable.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.