hangman
hangman

Reputation: 875

treating array keys as different variable in php

I have one dimensional array as below

$arr=array("a"=>'1',"b"=>2,'c'=>'3');

i need to use keys of array i.e a,b,c as variable .. so that

echo $a should display 1 , $b should display 2 and so on

possible in php?

Upvotes: 0

Views: 51

Answers (4)

Onimusha
Onimusha

Reputation: 3385

I just do it like this for basic arrays

$arr=array("a"=>'1',"b"=>2,'c'=>'3');
foreach($arr as $k=$v){ $$k=$v; }

echo $a; //prints 1
echo $c; //prints 3

EDIT: Check FDL's answer

Upvotes: 1

cortexjesse
cortexjesse

Reputation: 171

There is a built-in function for this called extract()

https://www.php.net/manual/en/function.extract.php

Upvotes: 2

ɴᴀᴛᴇ ᴅᴇᴠ
ɴᴀᴛᴇ ᴅᴇᴠ

Reputation: 4621

Just use extract():

$arr = array(
    'a' => 1,
    'b' => 2,
    'c' => 3
);
extract($arr);

echo $a; // = 1

Upvotes: 4

Cfreak
Cfreak

Reputation: 19319

extract($arr)

Is the correct answer to this question.

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

Its generally not considered a good idea though. Whats wrong with $arr['a']?

Upvotes: 4

Related Questions