0

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?

4 Answers 4

4

Just use extract():

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

echo $a; // = 1
Sign up to request clarification or add additional context in comments.

1 Comment

Wow thanks for this.. miles better than my answer. +1
4

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']?

Comments

2

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

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

Comments

1

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

1 Comment

@downvoter - please share why you downvoted since the above does work and I've used it flawlessly as long as I can remember. I also sent the questioner to what I feel is a better answer than mine (FDL)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.