PHP multi-variables assignment for "key => value" array - php

PHP's list keyword is nice for taking out variables from an array $a as below
$a = array(1,22);
list($b, $c) = $a;
var_dump("$a $b $c");
But for array $a2 in the form of key => value as below, I failed to use list
$a2 = array('b'=>1,'c'=>22);
list($b, $c) = $a2;
list($bkey, $b, $ckey, $c) = $a2;
list( list($bkey, $b), list($ckey,$c) ) = $a2;
var_dump("$a2 $b $c");
All of the three above assignments fail. I give up.
If you know how to get the key & value in array $a2, please help!

Following the comment of Mr Evil below (Col Shrapnel, see his profile), I never said following two ways are different, one could use either but I have advised using these methods on user-inputted data could create security problems, use it on your own risk or if there is no user-inputted data.
It does not seem to work with associatieve arrays, you can do something like this though:
foreach ($array as $key => $value) {
$$key = $value;
}
Example:
$a2 = array('b'=>1,'c'=>22);
foreach ($a2 as $key => $value) {
$$key = $value;
}
echo $b . '<br>';
echo $c;
Result:
1
22
One could also use extract() function but I generally avoid it because using it on user-inputted values could create security hazards. Depending on your choice, you might want to use it or if data isn't coming from users side.

I think you should use each function.
each() Return the current key and value pair from an array and advance the array cursor.

it seems it is extract() function you need

Related

How to combine array values and separate constants without using foreach construction?

I'm trying to find a simpler way to create new arrays from existing arrays and values. There are two routines I'd like to optimize that are similar in construction. The form of the first one is:
$i = 0;
$new_array = array();
foreach ($my_array as $value) {
$new_array[$i][0] = $constant; // defined previously and unchanging
$new_array[$i][1] = $value; // different for each index of $my_array
$i++;
}
The form of the second one has not one but two different values per constant; notice that $value comes before $key in the indexing:
$i = 0;
$new_array = array();
foreach ($my_array as $key => $value) {
$new_array[$i][0] = $constant; // defined previously and unchanging
$new_array[$i][1] = $value; // different for each index of $my_array
$new_array[$i][2] = $key; // different for each index of $my_array
$i++;
}
Is there a way to optimize these procedures with shorter and more efficient routines using the array operators of PHP? (There are many, of course, and I can't find one that seems to fit the bill.)
I believe a combination of Wouter Thielen's suggestions regarding the other solutions actually holds the best answer for me.
For the first case I provided:
$new_array = array();
// $my_array is numeric, so $key will be index count:
foreach ($my_array as $key => $value) {
$new_array[$key] = array($constant, $value);
};
For the second case I provided:
// $my_array is associative, so $key will initially be a text index (or similar):
$new_array = array();
foreach ($my_array as $key => $value) {
$new_array[$key] = array($constant, $value, $key);
};
// This converts the indexes to consecutive integers starting with 0:
$new_array = array_values($new_array);
it is shorter, when you use the array-key instead of the $i-counter
$new_array = array();
foreach ($my_array as $key => $value) {
$new_array[$key][0] = $constant; // defined previously and unchanging
$new_array[$key][1] = $value; // different for each index of $my_array
}
Use array_map:
$new_array = array_map(function($v) use ($constant) {
return array($constant, $v);
}, $my_array);
If you want to use the keys too, for your second case:
$new_array = array_map(function($k, $v) use ($constant) {
return array($constant, $v, $k);
}, array_keys($my_array), $my_array);
Assuming the $constant variable is defined in the caller's scope, you'll need to use use ($constant) to pass it into the function's scope.
array_walk is similar, but modifies the array you pass to it, so if you want to update $my_array itself, use array_walk. Your second case then becomes this:
array_walk($my_array, function(&$val, $key) use($constant) {
$val = array($constant, $val, $key);
});
In both examples above for the second case, you'll end up with an associative array (i.e. with the keys still being the keys for the array). If you want to convert this into a numerically indexed array, use array_values:
$numerically_indexed = array_values($associative);
I asked a question similar to this a few days ago, check it out:
PHP - Fastest way to convert a 2d array into a 3d array that is grouped by a specific value
I think that you have an optimal way when it comes to dealing with large amount of data. For smaller amounts there is a better way as was suggested by the benchmarks in my question.
I think too that readability and understanding the code can also be an issue here and I find that things that you can understand are worth more later on than ideas that you do not really grasp as it generally takes a long time to understand them again as it can be quite confusing while debugging issues.
I would suggest, you take a look at the differences between JSON encoded arrays and serialised arrays as there can be major performance differences when working with the two. It seems that as it is now JSON encoded arrays are a more optimised format (faster) for holding and working with data however this will likely change with PHP 7. It would be useful to note that they are also more portable.
Further Reading:
Preferred method to store PHP arrays (json_encode vs serialize)
http://techblog.procurios.nl/k/n618/news/view/34972/14863/cache-a-large-array-json-serialize-or-var_export.html

php how to generate dynamic list()?

base on my understanding, this how list() work.
list($A1,$A2,$A3) = array($B1,B2,B3);
So with the help of list() we can assign value out from array accordingly.
here is my question... how to generate a dynamic list()?
1). base on database return result, I'm not sure how many of it but I assign it all into array
2). so we can use count(array) to know how many of it.
3). so then HOW CAN I GENERATE/PREPARE a list for it?
Example: client A, have 3 kids, name Apple, Boy, Cat
so I use list($kid1, $kid2, $kid3) for it.
but when client B, have more then 3 kids, I only get first 3
or if client C, have only 1 kids, then error encounter.
I know if base on the situation above, there is many way to solve it without using list()
but I wish to know or find out the solution with using list().
How to generate dynamic list() base on count of array()
thanks guys/gals
If you have a variable number of elements, use arrays for them! It does not make sense to extract them into individual variables if you do not know how many variables you'll be dealing with. Say you did extract those values into variables $kid1 through $kidN, what is the code following this going to do? You have no idea how many variables there are in the scope now, and you have no practical method of finding out or iterating them next to testing whether $kid1 through $kidN are isset or not. That's insane use of variables. Just use arrays.
Having said that, variable variables:
$i = 1;
foreach ($array as $value) {
$varname = 'kid' . $i++;
$$varname = $value;
}
You can create a lambda expression with create_function() for this. The list() will be only accessible within the expression.
This creates variables $A1, $A2, .... $AN for each element in your array:
$list = array("a", "b", "c", "d");
extract(array_combine(array_map(function($i) {
return "A" . $i;
}, range(1, count($list))), $list));
echo implode(" ", array($A1, $A2, $A3, $A4)), PHP_EOL;
You can modify the name of the variables in the array_map callback. I hope I'll never see code like that in production ;)
This is not what PHP's list is meant for. From the official PHP docs
list is not really a function, but a language construct.
list() is used to assign a list of variables in one operation.
In other words, the compiler does not actually invoke a function but directly compiles your code into allocations for variables and assignment.
You can specifically skip to a given element, by setting commas as follows:
list($var1, , $var2) = Array($B1, B2, B3);
echo "$var1 is before $var2 \n";
or take the third element
list( , , $var3) = Array($B1, B2, B3);
(I am assuming B2, B3 are constants? Or are you missing a $?)
Specifically using list, you can use PHP's variable variables to create variables from an arbitrary one-dimensional array as follows:
$arr = array("arrindex0" => "apple", "banana", "pear");
reset($arr);
while (list($key, $val) = each($arr)) {
$key = is_numeric($key) ? "someprefix_" . $key : $key;
echo "key sdf: $key <br />\n";
$$key = $val;
}
var_dump($arrindex0, $someprefix_0, $someprefix_1);
Result
string 'apple' (length=5)
string 'banana' (length=6)
string 'pear' (length=4)

PHP how to loop through assoc array without replicating variables?

This would be easy to do with regular array with a simple for statement. EG:
$b= array('A','B','C');
$s=sizeof($b);
for ($i=0; $i <$s ; $i++) $b[$i]='your_face';
print_r($b);
But if I use assoc array, I can't seem any easy way to do it. I could, of course use a foreach loop, but it is actually replicating the $value variables instead of returning a pointer to an actual array entity. EG, this will not work:
$b= array('A'=>'A','B'=>'B','C'=>'C');
foreach ($b as $v) $v='your_face';
print_r($b);
Of course we could have some stupid idea like this:
$b= array('A'=>'A','B'=>'B','C'=>'C');
foreach ($b as $k => $v) $b[$k]='your_face';
print_r($b);
But this would be an awkward solution, because it would redundantly recreate $v variables which are never used.
So, what's a better way to loop through an assoc?
You could try:
foreach(array_keys($b) as $k) {
$b[$k] = 'your_face';
}
print_r($b);
See the following link for an explaination of array_keys: http://php.net/manual/en/function.array-keys.php
Not sure if that's what you want, but here goes:
foreach(array_keys($b) as $k) $b[$k] = 'your_face';

array notation differences php

What is the difference in the following array notations: $arr[$key] = $value and $arr[] = $value, which is a better way ?
function test(){
$key = 0;
$a = array(1,2,3,4,5);
foreach($a as $value){
$a[$key] = $value;
$key++;
}
print_r($a);
}
versus
function test(){
$a = array(1,2,3,4,5);
foreach($a as $value){
$a[] = $value;
}
print_r($a);
}
They are different.
$a[] = 'foo';
Adds an element to the end of the array, creating a new key for it (and increasing the overall size of the array). This is the same as array_push($array, 'foo');
$key = 0;
$a[$key] = 'foo';
Sets the 0 element of the array to foo, it overwrites the value in that location... The overall size of the array stays the same... This is the same as $array = array_slice($array, 0, 1, 'foo'); (but don't use that syntax)...
In your specific case, they are doing 2 different things. The first test function will result in an array array(1,2,3,4,5), whereas the second one will result in array(1,2,3,4,5,1,2,3,4,5). [] always adds new elemements to the end.... [$key] always sets....
$arr[$key] = $value sets a specific key to a specific value.
$arr[] = $value adds a value on to the end of the array.
Neither is "better". They serve completely different roles. This is like comparing writing and drawing. You use a pen for both of them, but which you use depends on the circumstance.
One ($a[$key] = $value) youare specifying the $key where PHP will override that array entry if you use the same key twice.
The other ($a[] = $value) PHP is handling the keys itself and just adding the array entry using the next available key.
The whole thing that you are doing is a bit redundant though, as in the first example you are trying to loop through the array setting its values to itself. In the second example you are duplicating the array.
If you want to append an element to the array I would use
$arr[] = $value;
It is simpler and you get all the information on that line and don't have to know what $key is.

PHP: Apply a function to multiple variables without using an array

I have a function (for ease, I'll just use count()) that I want to apply to maybe 4-5 different variables. Right now, I am doing this:
$a = count($a);
$b = count($b);
$c = count($c);
$d = count($d);
Is there a better way? I know arrays can use the array_map function, but I want the values to remain as separate values, instead of values inside of an array.
Thanks.
I know you said you don't want the values to be in an array, but how about just creating an array specifically for looping through the values? i.e.:
$arr = Array($a, $b, $c, $d);
foreach ($arr as &$var)
{
$var = count($var);
}
I'm not sure if that really is much tidier than the original way, though.
If you have a bunch of repeating variables to collect data your code is poorly designed and should just be using an array to store the values, instead of dozens of variables. So perhaps you want something like:
$totals = array("Visa"=>0,"Mastercard"=>0,"Discover"=>0,"AmericanExpress"=>0);
then you simply add to your array element (say from a while loop from your SQL or whatever you are doing)
$totals['Visa'] += $row['total'];
But if you really want to go down this route, you could use the tools given to you, if you want to do this with a large batch then an array is a good choice. Then foreach the array and use variable variables, like so:
$variables = array('a','b','c'...);
foreach ( $variables as $var )
{
${$var} = count(${var});
}
What Ben and TravisO said, but use array_walk for a little cleaner code:
$arr = Array($a, $b, $c, $d);
array_walk($arr, count);
You can use extract to get the values back out again.
//test data
$a = range(1, rand(4,9));
$b = range(1, rand(4,9));
$c = range(1, rand(4,9));
//the code
$arr = array('a' => $a, 'b' => $b, 'c' => $c);
$arr = array_map('count', $arr);
extract($arr);
//whats the count now then?
echo "a is $a, b is $b and c is $c.\n";
How do you measure "better"? You might be able to come up with something clever and shorter, but what you have seems like it's easiest to understand, which is job 1. I'd leave it as it is, but assign to new variables (e.g. $sum_a, ...).

Categories