PHP Variable Variables with Array Key

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 new variables from array keys in PHP

<?php extract($array); ?>

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

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

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];

}

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.

PHP Variable Variables and Array Index

echo ${"array_$array_numerals[$i]"}[$j];

But I must warn you that it is a very bad idea to do this.
Rather, use another lookup array:

$array = Array(
0 => Array(
2 => "$100",
...
),
...
);

echo $array[$i][$j];

How to search array keys with variable part of name?

please try this, and let me know if it works for you.

$arr1 = [
'g_0_q_2345' => [
'aaa' => 'bbb'
],
'g_0_q_5555' => [
'ccc' => 'ddd'
],
'g_0_qc_2222' => [
'eee' => 'fff'
]
];
$arr2 = [
'g_0_q_2345' => 1111,
'g_1_q_2345' => 2222,
'g_0_q_5555' => 3333
];

$keys1 = array_keys($arr1);
$keys2 = array_keys($arr2);

$search_keys = array_unique(array_merge($keys1,$keys2));

$result = [];
foreach($arr2 as $key=>$val){
if(in_array($key, $search_keys)){
$result[] = $val;
}
}

print_r($result);

PHP: Use Variable as Multiple Keys in Multi-Dimensional-Array

i think this solution is good.

note that you have to wrap all keys with "[" and "]".

$array = array(
'example' => array(
'secondDimension' => array(
'thirdDimension' => 'Hello from 3rd dimension',
)
),
);

function array_get_value_from_plain_keys($array, $keys)
{
$result;

$keys = str_replace(array('[', ']'), array("['", "']"), $keys); // wrapping with "'" (single qoutes)

eval('$result = $array' . $keys . ';');

return $result;
}

$keys = '[example][secondDimension][thirdDimension]'; // wrap 1st key with "[" and "]"
echo array_get_value_from_plain_keys($array, $keys);

Learn more about eval() function

if you also want to check if the value is defined or not then you can use this function

function array_check_is_value_set_from_plain_keys($array, $keys)
{
$result;

$keys = str_replace(array('[', ']'), array("['", "']"), $keys); // wrapping with "'" (single qoutes)

eval('$result = isset($array' . $keys . ');');

return $result;
}

Giving a better name to that function will be appreciated ^^



Related Topics



Leave a reply



Submit