'Printing more than one array using print_r or any other function in php

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



Solution 1:[1]

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"]

Solution 2:[2]

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

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 John Conde
Solution 3 Salem