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!


Solution 1:

<?php extract($array); ?>

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

Solution 2:

You could do this:

foreach($foo as $k => $v) {
  $$k = $v;
}

Solution 3:

A simple method is to use variable variables:

foreach($foo as $key => $value) {
   $$key = $value;
}

echo $first; // '1st'

Note that this is generally discouraged however. It would be better to alter your templating system to allow for variables to be scoped within the template. Otherwise you could have issues with collisions and have to test for their existence, etc.