phparraysprintfvar-dump

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

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