Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If I have an array

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

Is there any way of doing this in PHP

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

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

Eg, variables would be available like so

echo $year;
2012
echo $place;
school
like image 829
Nick Shears Avatar asked Feb 14 '23 16:02

Nick Shears


2 Answers

Use extract

extract($places)

echo $year;

echo $place;

Or, you could use variable-variables:

foreach ($places as $key => $value) 
{
  $$key = $value //note the $$
}
like image 118
dave Avatar answered Feb 17 '23 11:02

dave


Why can't you just do like this ?

<?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.

like image 33
Shankar Narayana Damodaran Avatar answered Feb 17 '23 10:02

Shankar Narayana Damodaran