How to set variables inside foreach loop for external access in PHP?

If i have an array

$places = array('year' => '2012', 'place' => 'school');

Is there any way to do this in PHP

foreach ($places as $key => $value) 
{
    $key = $value
}

But so that the variables are set based on the key name.

For example, variables will be available this way.

echo $year;
2012
echo $place;
school
+4
source share
2 answers

Use extract

extract($places)

echo $year;

echo $place;

Or you can use variable variables:

foreach ($places as $key => $value) 
{
  $$key = $value //note the $$
}
+5
source

Why can't you just do it?

<?php
$places = array('year' => '2012', 'place' => 'school');
echo $places['year'];// prints 2012 This is also synonymous to a variable

AFAIK, you are just complicating your example.

+3
source

All Articles