Derek Maciel Derek Maciel - 2 days ago 4
PHP Question

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!

Answer
<?php extract($array); ?>

http://php.net/extract

Comments