W3docs

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.

In PHP, you can use the $array[$key] syntax to get the value stored at a particular key in an array. For example:

Example of finding array value using the key in PHP

<?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:

Example of using isset() function to check if a particular key is set in an array in PHP

<?php

$fruits = ['apple' => 'red', 'banana' => 'yellow', 'orange' => 'orange'];
if (isset($fruits['apple'])) {
  echo "The value for key 'apple' is set in the array.";
}

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

If you want to get all the values in an array, you can use the array_values() function:

Example of using array_values() function to get all the values in an array in PHP

<?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:

Example of using array_keys() function to get all the keys in an array in PHP

<?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:

Example of using "foreach" to loop through an array and get both the keys and values in PHP

<?php

$fruits = ['apple' => 'red', 'banana' => 'yellow', 'orange' => 'orange'];
foreach ($fruits as $key => $value) {
  echo "Key: $key; Value: $value\n";
}