Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP how to get value from array if key is in a variable

Tags:

arrays

php

I have a key stored in a variable like so:

$key = 4;

I tried to get the relevant value like so:

$value = $array[$key];

but it failed. Help.

like image 658
Mazatec Avatar asked Feb 17 '10 14:02

Mazatec


People also ask

How get key from value in array in PHP?

If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).

How do you access a key in an array?

If you want to access the key of an array in a foreach loop, you use the following syntax: foreach ($array as $key => $value) { ... }

How do you check if a key is present in an array in PHP?

PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

How do you find the specific value of an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.


1 Answers

Your code seems to be fine, make sure that key you specify really exists in the array or such key has a value in your array eg:

$array = array(4 => 'Hello There');
print_r(array_keys($array));
// or better
print_r($array);

Output:

Array
(
    [0] => 4
)

Now:

$key = 4;
$value = $array[$key];
print $value;

Output:

Hello There
like image 64
Sarfraz Avatar answered Sep 30 '22 12:09

Sarfraz