PHP – Check if Array Key Exists
In PHP, we can check if a specific key exists in an array using the array_key_exists()
function which is a built in function in PHP or by using another built in isset()
function. Here’s how you can use both methods:
Method 1: Using array_key_exists() function
array_key_exists()
function is a built-in PHP function used to check if a specific key exists in an array. It takes two parameters: the key we want to check for, and the array we want to search in. The function returns true
if the key exists in the array, and false
if the key doesn’t exist in the array.
<?php // define or make the array $students = array( 'name' => 'John Doe', 'roll' => '101', 'class' => '9' ); // Using array_key_exists() if (array_key_exists('roll', $students)) { echo "Key 'roll' exists in the array."; } else { echo "Key 'roll' does not exist in the array."; } echo "<br>"; ?>
Method 2: Using isset() function
The isset()
function is a widely used function in PHP. The isset()
function in PHP is used to determine if a variable is set and is not NULL. It returns true
if the variable exists and has a value other than NULL
, and false
otherwise. This function can accept multiple parameters, and it checks each parameter separately.
<?php // Using isset() function define or make the array $students = array( 'name' => 'John Doe', 'roll' => '101', 'class' => '9' ); if (isset($students['class'])) { echo "Key 'class' exists in the array."; } else { echo "Key 'class' does not exist in the array."; } ?>
Both methods example output will output that the array key exists in out cases.
Check Out More Resources:
Articles:
Website: https://laravelplug.com/
YouTube Channel: https://www.youtube.com/channel/UCnTxncHQcBSNs4RCuhWgF-A?sub_confirmation=1
WordPress Playlist: https://www.youtube.com/watch?v=8VvXzFAFwQU&list=PLVoVZqAh8dTLHZ51egvEU7dsOrRCSIMWx
Tools Playlist: https://www.youtube.com/watch?v=gTQoUn3BQkM&list=PLVoVZqAh8dTK-DWHBGWOEEvzvPQrgFne-
WordPress Tutorials: https://laravelplug.com/category/wordpress/
Laravel Tutorials: https://laravelplug.com/category/laravel/
PHP Tutorials: https://laravelplug.com/category/php/
SQL Tutorials: https://laravelplug.com/category/sql/
Various Tips: https://laravelplug.com/category/tips/
Useful Tools: https://laravelplug.com/category/tools/
Socials:
Twitter: https://twitter.com/LaravelPlug
Pinterest: https://www.pinterest.com/LaravelPlugCom/
Facebook: https://www.facebook.com/groups/1020759861842360
Mail: info@laravelplug.com
#PHP #array
That’s All. Feel free to knock me. Thanks.