Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export array key and value as variable name and value

Tags:

arrays

php

considering this array :

$segments = array(
    "key1"    =>"111",
    "key2"    =>"222",
    "key3"    =>"333",
    "key4"    =>"444"
);

I want to have these:

$key1 has the value of "111";

$key2 has the value of "222";

$key3 has the value of "333";

$key4 has the value of "444";

What can I do ?

like image 684
John Avatar asked Oct 06 '11 00:10

John


People also ask

How do you find the key and value of an array?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

What is the use of extract () function?

The extract() function imports variables into the local symbol table from an array. This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table. This function returns the number of variables extracted on success.

Can an array be a key?

No. Arrays can only have integers and strings as keys.

Can array key be an array?

This is not possible - array keys must be strings or integers.


2 Answers

PHP has a built-in function that does exactly this:

extract($segments);

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

like image 159
Amber Avatar answered Oct 13 '22 22:10

Amber


use

extract($segments)

References:

  • extract Extract the keys of an hash array into the corresponding variables
  • compact Does the reverse thing
like image 31
Eineki Avatar answered Oct 13 '22 23:10

Eineki