array(
array('foo' => '11'),
array('bar' => '22'),
);
Given the array above, without using a loop, is it possible to output the following string?
'11 22'
You have to use array_reduce method
Solution :
<?php
$a = array(
array('foo' => '11'),
array('bar' => '22'),
);
function glue($carry, $item){
$carry .= array_values($item)[0]." ";
return $carry;
};
var_dump(trim(array_reduce($a, "glue", "")));
?>
Very simple, you have a multi dimensional array. Your top-level array has two elements (which are also arrays) with the index of '0' and '1' respectively.
Your child array is an associative array so instead of having an index of 0, 1, 2 ...n you have an index of 'foo' and 'bar' respectively.
So if you want to display the number 11...
$array = array(
array('foo' => '11'),
array('bar' => '22'),
);
echo $array[0]['foo'];
To make it into a sentence you would concatenate your two array elements
$array = array(
array('foo' => '11'),
array('bar' => '22'),
);
echo $array[0]['foo'] . ' ' . $array[1]['bar'];
echo "'{$arr[0]['foo']} {$arr[1]['bar']}'"$string = ''; $counter = 0; array_walk_recursive($dataArray, function ($value) use (&$string, &$counter) { $string .= ($counter ? ' ' : '') . $value; ++$counter; }); var_dump($string);Implodeseemed like it could work, but I couldn't see how. Maybe a loop is the best way.