Printing more than one array using print_r or any other function in php
Asked Answered
K

3

8

I need to print contents of multiple arrays in my code. Eg

   function performOp($n, $inputArr, $workArr)
    {
        printf("Entered function, value of n is %d", $n);
    print_r($inputArr);
    print_r($workArr);
        $width =0;
    }

Now, Instead of writing print_r twice, is there any way I can write a single statement and print both the arrays ? Also, If I want to print "Input array value is " before displaying the Array{}, is there a way to do so using printf or any other function?

I tried writing

    printf("Value of inputArray is %s ", print_r($inputArr)
, but this would not work.

Any help is really appreciated.

Thanks

Knap answered 4/5, 2012 at 2:7 Comment(0)
C
4

Dumping the Variables

You can pass multiple arrays into var_dump().

var_dump( $array, $array2, $array3 );

For instance, the following:

$array = array("Foo", "bar");
$array2 = array("Fizz", "Buzz");

var_dump( $array, $array2 );

Outputs this:

array(2) { [0]=> string(3) "Foo" [1]=> string(3) "bar" }
array(2) { [0]=> string(4) "Fizz" [1]=> string(4) "Buzz" }

Note how it keeps both arrays distinct in the output as well.

Function with n-arguments

You could also use a function, calling upon func_get_args() for the arrays passed in:

function logArrays() {
  $arrays = func_get_args();
  for ( $i = 0; $i < func_num_args(); $i++ )
    printf( "Array #%d is %s", $i, print_r($arrays[$i], true) );
}

logArrays( $array, $array2 );

Which, in this case, would output the following:

Array #0 is Array ( [0] => Foo  [1] => bar  )
Array #1 is Array ( [0] => Fizz [1] => Buzz )

Using json_encode() instead of print_r would output a slightly more readable format:

Array #0 is ["Foo","bar"]
Array #1 is ["Fizz","Buzz"]
Corncob answered 4/5, 2012 at 2:10 Comment(2)
This is a good option, but I do not want to print that much detail. I want to print a log statement saying that my array named ABC is {} and my array named XYZ is {}Knap
This is awesome! I tried writing the logArrays() function with both print_r and json_encode() and they work fine. Thank you so much!Knap
L
1

User array_merge() to combine the arrays and then you can print them together.

Lawless answered 4/5, 2012 at 2:10 Comment(0)
W
0

If you prefer to use less function and have the advantage and simplicity of print_r() you combine these input value into new array inside the print_r(), e.g I use this function to print raw unformatted output if my code (for debug) and this is the easiest method I reach.

function  pre( $txt ) {
  print_r( [ '<xmp> ' , $txt ,' </xmp> ' ] );
   }
Waterhouse answered 18/4, 2022 at 17:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.