1
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.

Joe T
  • 2,300
  • 1
  • 19
  • 31
daily-learner
  • 617
  • 1
  • 8
  • 17
  • "Get into" how exactly? Put them into an array? `array_column`. – Jon Jul 02 '13 at 22:35
  • Really unclear. Could be implode, or $test my be what you're after. Can you explain more? (Or just "echo" stuff out to see what's what) – Robbie Mar 05 '14 at 12:51

5 Answers5

2

you're overwriting $var on each iteration. with a dot as follows, this will append instead of overwrite.
$var .= $test['somekey'];

Joe T
  • 2,300
  • 1
  • 19
  • 31
2

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!

meiamsome
  • 2,876
  • 1
  • 17
  • 19
  • A simple answer that saved my day. Thanks!! thats awesome that array [] brackets is what I needed – NJENGAH Jul 28 '20 at 22:17
1

How about:

$data = array() ;
foreach ($tests as $test) {
  $data[] = $test['somekey'];
}

echo implode(" ; ", $data) ;
sybear
  • 7,837
  • 1
  • 22
  • 38
0

You can try :

$var = array_map(function ($v) {
    return $v['somekey'];
}, $tests);

echo implode(PHP_EOL, $var);
Baba
  • 94,024
  • 28
  • 166
  • 217
0

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>");
Saturnix
  • 10,130
  • 17
  • 64
  • 120