Suppose I have an array, like this:
$foo = array('first' => '1st', 'second' => '2nd', 'third' => '3rd');
How can I pick the keys out of the array and make them their own variables? For example, the array $foo
would become:
$first = '1st'; $second = '2nd'; $third = '3rd';
I ask this because I am creating an MVC framework to help with my OOP, and I would like the user to pass a variable to the View loading function, which will allow the user to use variables in the template without having to know what the array was called.
For example:
$array = array('title' => 'My blog!' [...]); $this->load->view('view.php', $array);
view.php:
echo $title;
Output:
My blog!
The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.
Calling setVal($data,array('foo','bar','2017-08'),'hello') will set value as if you called $data['foo']['bar']['2017-08'] = 'hello' . non-existent keys will be created automatically by php magic. This can be useful if you want to build the structure of the array dynamically.
array_keys() returns the keys, numeric and string, from the array . If a search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.
The extract() function imports variables into the local symbol table from an array. This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table. This function returns the number of variables extracted on success.
<?php extract($array); ?>
http://php.net/manual/en/function.extract.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With