Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new variables from array keys in PHP

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!

like image 378
Derek Maciel Avatar asked Feb 06 '11 22:02

Derek Maciel


People also ask

What is array_keys () used for?

The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.

How do you set an array key?

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.

What is an array key PHP?

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.

What is the use of extract () function?

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.


1 Answers

<?php extract($array); ?> 

http://php.net/manual/en/function.extract.php

like image 170
KomarSerjio Avatar answered Oct 14 '22 07:10

KomarSerjio