-3

I have an associative array like this:

$myarray = array('a' => 1, 'b' => 2, 'c' => 3);

And I want to show the array keys and values like this:

a is 1, b is 2, c is 3

I don't want to do this by using print_r or var_dump. And I don't want to use a foreach loop too. I just want to use a short code, I have tried this:

echo implode('', $myarray);

But that doesn't work too, because I can only display the key or only display the value of the array.

celalk38
  • 81
  • 8

3 Answers3

5

Check this one liner,

echo implode(',', array_map(function ($a, $b) { return "$a is $b"; }, 
array_keys($myarray),array_values($myarray)));

array_map — Applies the callback to the elements of the given arrays
array_values — Return all the values of an array
array_keys — Return all the keys or a subset of the keys of an array
implode — Join array elements with a string

Working code.

Rahul
  • 18,271
  • 7
  • 41
  • 60
  • 3
    That's rather over the top isn't it? If it's just a question of being one line `foreach($myarray as $key => $value) { echo "$a is $b";}` is shorter, and simpler. – Jonnix Mar 07 '19 at 08:51
  • I agree with you. But he didn't mention short or long. Specifically *No For/Foreach* loop. So I did that. :) – Rahul Mar 07 '19 at 08:54
  • May I know, where? – Rahul Mar 07 '19 at 08:55
  • `without using a foreach or other function?` right there in the title. – Jonnix Mar 07 '19 at 08:55
  • Oh Yes, title. Okay. I will see another way around. But if OP is happy, its Ok. – Rahul Mar 07 '19 at 08:56
  • 2
    OP also said `I just want to use a short code`. So short or long is mentioned. It's fine if OP finds the answer helpful (it was a silly question to begin with). – Jonnix Mar 07 '19 at 08:59
0

Try This,

array_walk($myarray,'test_print');
function test_print($value, $key) {
    echo "$key is $value\n";
}

Tried and tested CODE

M.Hemant
  • 2,345
  • 1
  • 9
  • 14
0

Because PHP has so many core functions this can be done in so many different ways, but here is one that I have found to be faster than most others...

<?php

$myarray = array ( 'a' => 1, 'b' => 2, 'c' => 3 );

echo str_replace ( array ( '&', '=' ), array ( ', ', ' is ' ), http_build_query ( $myarray ) );

?>
  • Interesting approach, but the problem with this is that it will encode keys and values as if it were a URL, so may not produce your desired output. – Progrock Mar 09 '19 at 06:23