How to find array / dictionary value using key?
In PHP, you can use the $array[$key]
syntax to get the value stored at a particular key in an array. For example:
<?php
$fruits = ['apple' => 'red', 'banana' => 'yellow', 'orange' => 'orange'];
echo $fruits['apple'] . PHP_EOL; // outputs 'red'
echo $fruits['orange']; // outputs 'orange'
You can also use the isset()
function to check if a particular key is set in an array:
<?php
$fruits = ['apple' => 'red', 'banana' => 'yellow', 'orange' => 'orange'];
if (isset($fruits['apple'])) {
echo "The value for key 'apple' is set in the array.";
}
Watch a video course
Learn object oriented PHP
If you want to get all the values in an array, you can use the array_values()
function:
<?php
$fruits = ['apple' => 'red', 'banana' => 'yellow', 'orange' => 'orange'];
$values = array_values($fruits);
print_r($values); // outputs: Array ( [0] => red [1] => yellow [2] => orange )
If you want to get all the keys in an array, you can use the array_keys()
function:
<?php
$fruits = ['apple' => 'red', 'banana' => 'yellow', 'orange' => 'orange'];
$keys = array_keys($fruits);
print_r($keys); // outputs: Array ( [0] => apple [1] => banana [2] => orange )
If you want to loop through an array and get both the keys and values, you can use a foreach loop:
<?php
$fruits = ['apple' => 'red', 'banana' => 'yellow', 'orange' => 'orange'];
foreach ($fruits as $key => $value) {
echo "Key: $key; Value: $value\n";
}