Create New Variables from Array Keys in PHP

Create new variables from array keys in PHP

<?php extract($array); ?>

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

Array key = variable name

PHP supports variable variables, although this is poor design you can just do:

foreach ($data as $key => $value) {

$$key = $data[$key];

}

set variable variable as array key

on topic to your question. With the logic of PHP, the best way I can see this being done is to assign your variable variables outside the array definition:

$id = 1;
$age = 2;
$sort = "id"; // or "age";
$Key = $$sort;
$arr = array($Key => 'string');

print_r($arr);

Which outputs:

Array ( [1] => string )

Though, personally. I'd suggest avoiding this method. It would be best to define your keys explicitly, to assist with backtracing/debugging code. Last thing you want to do, is to be looking through a maze of variable-variables. Especially, if they are created on the fly


Tinkering. I've got this;

$arr[$$sort] = "Value";

print_r($arr);

I've looked into the method to creating a function. I do not see a viable method to do this sucessfully. With the information i've provided (defining out of array definition), hopefully this will steer you in the right direction

How to assign variable when creating PHP array with key and value

You don't have to do anything special.

Just write the name of the variable.

$zip = '252354';
$data = array(
'uid' => 'key',
'zip' => $zip,

"school" => array(
array("sid" => "STRING_VARIABLE", "qty" => NUMERIC_VARIABLE),
array("strSrchSchool" => array(
"name" => "STRING_VARIABLE",
"address" => "STRING_VARIABLE",
),
"students" => NUMERIC_VARIABLE)
),
"sort" => "default"
);

And so on you can write as many variables inside the array as you wish.

PHP Variable Variables with array key

The following is an example following your variable name syntax that resolves array members as well:

// String that has a value similar to an array key
$string = 'welcome["hello"]';

// initialize variable function (here on global variables store)
$vars = $varFunc($GLOBALS);

// alias variable specified by $string
$var = &$vars($string);

// set the variable
$var = 'World';

// show the variable
var_dump($welcome["hello"]); # string(5) "World"

With the following implementation:

/**
* @return closure
*/
$varFunc = function (array &$store) {
return function &($name) use (&$store)
{
$keys = preg_split('~("])?(\\["|$)~', $name, -1, PREG_SPLIT_NO_EMPTY);
$var = &$store;
foreach($keys as $key)
{
if (!is_array($var) || !array_key_exists($key, $var)) {
$var[$key] = NULL;
}
$var = &$var[$key];
}
return $var;
};
};

As you can not overload variables in PHP, you are limited to the expressiveness of PHP here, meaning there is no write context for variable references as function return values, which requires the additional aliasing:

$var = &$vars($string);

If something like this does not suit your needs, you need to patch PHP and if not an option, PHP is not offering the language features you're looking for.

See as well the related question: use strings to access (potentially large) multidimensional arrays.

Create a variable from each item in a PHP array

Something like this should do what I think you are trying to do.

$data = array(
array('first_name' => 'Arthur', 'last_name' => 'Dent', 'planet' => 'Earth'),
array('first_name' => 'Ford', 'last_name' => 'Prefect', 'planet' => 'Betelgeuse')
);

foreach( $data as $i => $arr ){
foreach( $arr as $key => $value ){
${$key . $i} = $value;
${$i . '_' . $key} = $value;
}
}
echo $first_name0, $first_name1, ${'0_first_name'};

Obviously, I have the integer after the name, but it's trivial to reverse them and have something like $0first_name or $0_first_name - but they need to be handled differently when outputting them - ${'1_first_name'}, etc. - again, as has been pointed out, - it is not the best approach for maintainability, so now I'll go off and rethink all the bad decisions I have made in life.

how to create array with key name same as $variable name assigning to array?

compact is the inverse of extract. Use it like this :

$array = compact ('one', 'two', 'three');

This will look for the variables named 'one', 'two', 'three', and does exactly what you are looking for.

Each value of an array as string variables in PHP

@asjoler's answer is quite effective and succinct. But if you want secondary control over the variable names, you can use list(). array_values() is also needed to get the numerical indexes that list() needs while keeping the natural order:

$a = array();

$a["comp"] = "Conseil clientèle en assurances";
$a["code"] = "abc";
$a["score"] = 2;

list($comp, $code, $score) = array_values($a);

echo $comp . ", ";
echo $code . ", ";
echo $score;

Outputs:

Conseil clientèle en assurances
abc
2


Related Topics



Leave a reply



Submit