-2

I'm not a big fan of using print_r and I prefer to use echo all the time when I can so how can I use echo with PHPs array_reverse() function

This how the docs look like most of the time online they use print_r all the time for example

<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));
?>

I tried to use echo with this example but it does not work with echo.

<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
echo array_reverse($a);
?>

So how can I get it to work with echo?

  • 1
    What do you expect to see as a result? `echo` can only print _strings_ (or types that can be implicitly casted to a string). – zerkms Jan 06 '19 at 20:00
  • You can't, at least it won't produce what you expect. `echo` can only output _scalar_ values, but you have a structured value. So you'd need to implement a wrapper around `echo` that converts the structure into scalar values, that in a recursive manner. – arkascha Jan 06 '19 at 20:00
  • https://3v4l.org/t1dSN - you really want to pick `var_dump` of these options. – Xatenev Jan 06 '19 at 20:03
  • 2
    Not sure how `array_reverse()` has any effect on the use of `echo` - it's more to do with `echo` and arrays. – Nigel Ren Jan 06 '19 at 20:13

2 Answers2

0

Short answer, you can't. You can join all the array elements in a string using the implode function, then echo it out.

<?php

$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");

$comma_separated = implode(", ", array_reverse($a));

echo $comma_separated;

?>

I've separated each array element by a comma.

Alternatively, for more control over the results, you can simply loop through the array using foreach, you can get an idea of how to do this here: How to echo an array in PHP?

Cesar Correchel
  • 513
  • 3
  • 7
0

You can't pass an array to echo; you have to traverse it and echo keys and/or values.

For a single level associative array like the one in the example this can be done like this:

<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");

foreach( array_reverse( $a ) as $key => $value ) {
    echo "$key: $value\n";
}

The output:

c: Toyota
b: BMW
a: Volvo

You may adjust the above code to format the output as you like.

Of course it won't work if the array contains other (nested) arrays or objects.


However if your need is for debugging purposes I suggest to stick with PHP's native functions available for that specific purpose:

print_r

var_export

var_dump

Paolo
  • 15,233
  • 27
  • 70
  • 91