Create new variables from array keys in PHP

PhpArraysVariables

Php Problem Overview


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!

Php Solutions


Solution 1 - Php

Solution 2 - Php

You could do this:

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

Solution 3 - Php

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.

Solution 4 - Php

In PHP 7.1, you can use the list() and it's shorthand to create new variable from array keys.

$foo = array('first' =>  '1st',
             'second' => '2nd',
             'third' =>  '3rd');
list('first' => $first, 'second' => $second, 'third' => $third) = $foo;
// $first = '1st'

// or use shorthand
['first' => $first, 'second' => $second, 'third' => $third] = $foo;

This gives you more control on pulling out variables from an array. For instance, you can pull out only 'first' and 'second' and skip other.

Solution 5 - Php

This is really an answer to my own question, but since it was marked as a duplicate, I was advised to post my answer here. (I do not have the privilege to post in meta.)

When you have a table in a database with many columns, it can be an hassle to make a variable for each one. The great thing is that you can make variables automatically!

This method uses the heading / title / name of the columns in a database table as variable names, and the content of the selected row as the variables' value.

This approach is suitable when you only select one row from the table. My code with comments:

$query = "SELECT * FROM mdlm WHERE mdlmnr = $id";  // Select only *one* row, the column mdlmnr is a unique key
$resultat = $conn->query($query); //Get the result (the connection is established earlier)

while ($col = $resultat->fetch_field()) { //fetch information about the columns
    $kolonnetittel = $col->name; //Set the variable as the name of the column
    echo $kolonnetittel . "<br>"; //Show all the column names/variables
}

$innhold = $resultat->fetch_assoc(); // get the content of the selected row as an array (not a multidimensional array!) 
extract($innhold, EXTR_PREFIX_SAME, "wddx"); // Extract the array

Since I'm no pro the code might not be the best, but it works for me :-) When the list of the variables appeared on my web page I copied it into Excel and used concatenate to make php/html/css-code: paragraphs with designated class for each variable. Then I copied this code back into the code of my web page, and moved every piece around. Before finishing I commented out this line:

//echo $kolonnetittel . "<br>"; 

Useful links:

I hope this '"tutorial" might help someone else!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDerek MacielView Question on Stackoverflow
Solution 1 - PhpKomarSerjioView Answer on Stackoverflow
Solution 2 - Phpxil3View Answer on Stackoverflow
Solution 3 - PhpHamishView Answer on Stackoverflow
Solution 4 - PhpSupun KavindaView Answer on Stackoverflow
Solution 5 - PhpIngeborgView Answer on Stackoverflow