1
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'
5
  • Check this out. php.net/manual/en/function.implode.php Commented Jul 25, 2016 at 16:00
  • 1
    echo "'{$arr[0]['foo']} {$arr[1]['bar']}'" Commented Jul 25, 2016 at 16:00
  • What are the edge cases? Does the outer array always contain one sub-array, or can it contain multiple arrays? If multiple, how to handle sepration between both? And why do you want it without a loop? Commented Jul 25, 2016 at 16:04
  • $string = ''; $counter = 0; array_walk_recursive($dataArray, function ($value) use (&$string, &$counter) { $string .= ($counter ? ' ' : '') . $value; ++$counter; }); var_dump($string); Commented Jul 25, 2016 at 16:06
  • I was wondering if there was a way of doing this with one short line of code. Implode seemed like it could work, but I couldn't see how. Maybe a loop is the best way. Commented Jul 25, 2016 at 16:13

3 Answers 3

3

Here's a one-liner:

$subject = array(
    array('foo' => '11'),
    array('bar' => '22'),
    array('bar' => '33'),
);

echo implode(" ", array_map("implode", $subject ));

11 22 33

Sign up to request clarification or add additional context in comments.

Comments

0

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", "")));
?>

Live example

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.