Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting values from associative array

Tags:

I have the following main array called $m

Array (     [0] => Array         (             [home] => Home         )      [1] => Array         (             [contact_us] => Contact Us         )      [2] => Array         (             [about_us] => About Us         )      [3] => Array         (             [feedback_form] => Feedback Form         )      [4] => Array         (             [enquiry_form] => Products         )      [5] => Array         (             [gallery] => Gallery         )  ) 

I have the values eg home, contact_us in a array stored $options , I need to get the values from the main array called $m using the $options array

eg. If the $options array has value home, i need to get the value Home from the main array ($m)

my code looks as follows

                    $c = 0;                     foreach($options as $o){                         echo $m[$c][$o];                         ++$c;                     } 

I somehow just can't receive the values from the main array?

like image 740
Elitmiar Avatar asked Oct 08 '09 10:10

Elitmiar


People also ask

How do you find a specific value in 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.

How can we define an associative array and assign a value to it?

Definition and Usage In PHP, an array is a comma separated collection of key => value pairs. Such an array is called Associative Array where value is associated to a unique key. The key part has to ba a string or integer, whereas value can be of any type, even another array. Use of key is optional.

Does In_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.

What is an associative array PHP?

Associative Array - It refers to an array with strings as an index. Rather than storing element values in a strict linear index order, this stores them in combination with key values. Multiple indices are used to access values in a multidimensional array, which contains one or more arrays.


1 Answers

I'd first transform $m to a simpler array with only one level:

$new_m = array(); foreach ($m as $item) {     foreach ($item as $key => $value) {         $new_m[$key] = $value;     }  } 

Then you can use:

foreach ($options as $o) {     echo $new_m[$o]; } 
like image 119
Lukáš Lalinský Avatar answered Oct 15 '22 17:10

Lukáš Lalinský