3

I know the printf statement in PHP can format strings as follows:

//my variable 
$car = "BMW X6";

printf("I drive a %s",$car); // prints I drive a BMW X6, 

However, when I try to print an array using printf, there does not seem to be a way to format it. Can anyone help?

mensch
  • 4,401
  • 3
  • 27
  • 49
Destiny Makuyana
  • 93
  • 1
  • 1
  • 5

5 Answers5

9

Here's an extract from one of the comments on http://php.net/manual/en/function.printf.php:

[Editor's Note: Or just use vprintf...]

If you want to do something like:

// this doesn't work
printf('There is a difference between %s and %s', array('good', 'evil'));   

Instead of

printf('There is a difference between %s and %s', 'good', 'evil'); 

You can use this function:

function printf_array($format, $arr) 
{ 
    return call_user_func_array('printf', array_merge((array)$format, $arr)); 
}  

Use it the following way:

$goodevil = array('good', 'evil'); 
printf_array('There is a difference between %s and %s', $goodevil); 

And it will print:

There is a difference between good and evil
Josh
  • 7,934
  • 5
  • 41
  • 40
Pateman
  • 2,589
  • 3
  • 28
  • 39
6

Are you looking for something like this using print_r with true parameter:

printf("My array is:***\n%s***\n", print_r($arr, true));
anubhava
  • 713,503
  • 59
  • 514
  • 593
4

You can't "print" an array just like that, you'll have to iterate through it by using foreach, then you can printf all you want with the values. For example:

$cars = array('BMW X6', 'Audi A4', 'Dodge Ram Van');
foreach($cars as $car) {
    printf("I drive a %s", $car);
}

This would output:

I drive a BMW X6

I drive a Audi A4

I drive a Dodge Ram Van

Oldskool
  • 33,525
  • 7
  • 51
  • 64
0

yes

On your html place this:

<pre>
  <?php 
   print_r ($your_array);
  ?>
</pre>

or on your code only place:

 print_r ($your_array);
workdreamer
  • 2,746
  • 1
  • 33
  • 37
0

printf does not handle an array recursively. You can however do:

$cars=array('Saab','Volvo','Koenigsegg');
print_r($cars);
Gustav
  • 2,814
  • 1
  • 23
  • 31