Friday, June 12, 2026
HomeLanguagesHow to get specific key value from array in PHP ?

How to get specific key value from array in PHP ?

In this article, we will see how to get specific key values from the given array. PHP array is a collection of items that are stored under keys. There are two possible types of keys: strings and integers. For any type of key, there is a common syntax to get a specific value by key — square brackets.

Example 1:

PHP




<?php
  
$mixedArr = [
    10,
    20,
    'hello' => 'world',
    30,
];
  
// Get a specific value by index
$firstItem = $mixedArr[0];
echo "An item by index 0: {$firstItem}\n";
  
// Get a specific value by string key
$stringItem = $mixedArr['hello'];
echo "An item by key 'hello': {$stringItem}\n";
  
?>


Output

An item by index 0: 10
An item by key 'hello': world

Example 2: Sometimes we can accidentally try to get a non-existent item from the array. In this case, PHP throws a NOTICE. To avoid the issue, we have to check the key existence before accessing it. 

PHP




<?php
  
$arr = [1, 2, 3];
  
// Check the key existence with 
// the built-in 'isset' function
if (isset($arr[10])) {
    echo "index 10 value is: {$arr[10]}\n";
} else {
    echo "There are no value under the index 10\n";
}
  
$value = $arr[10] ?? 'unknown';
  
echo "A value under the index 10: {$value}\n";
  
?>


Output

There are no value under the index 10
A value under the index 10: unknown
RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS