foreach ($tests as $test) {
$var = $test['somekey'];
}
echo $var;
How do I get all values of a foreach into a php variable? It seems to be picking up only the last variable.
foreach ($tests as $test) {
$var = $test['somekey'];
}
echo $var;
How do I get all values of a foreach into a php variable? It seems to be picking up only the last variable.
you're overwriting $var on each iteration. with a dot as follows, this will append instead of overwrite.
$var .= $test['somekey'];
The answer you're looking for depends on what you wish to do. If you wish for an array, use:
$var = array();
foreach ($tests as $test) {
$var[] = $test['somekey'];
}
print_r($var);
or if you have PHP version >= 5.5.0 you can use:
$var = array_column($tests, $test);
If you wish for a string, use:
$var = "";
foreach ($tests as $test) {
$var .= $test['somekey'];
}
print_r($var);
If you wish for a number, use:
$var = 0;
foreach ($tests as $test) {
$var += $test['somekey'];
}
print_r($var);
You could also use any of the Assignment Operators instead of the +=
to do whatever you wanted!
How about:
$data = array() ;
foreach ($tests as $test) {
$data[] = $test['somekey'];
}
echo implode(" ; ", $data) ;
You can try :
$var = array_map(function ($v) {
return $v['somekey'];
}, $tests);
echo implode(PHP_EOL, $var);
it seems to be picking up the last variable only
That's because $var
is a variable, not an array. You're just overriding the same variable multiple times: the only value which will remain is the last one.
Convert $var
to an array in your code.
$var = new array();
then use something like array_push
to add the value in the array
foreach ($tests as $test) {
array_push($var, $test['somekey']);
}
finally, you may want to print out the value. echo
is not the ideal way to print out an array. I'd recommend using print_r or var_dump enclosed in <pre>
tags.
echo ("<pre>");
var_dump($var);
echo ("</pre>");