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,411
  • 3
  • 28
  • 49
Destiny Makuyana
  • 93
  • 1
  • 1
  • 5
  • 1
    What kind of formatting would you expect to happen on an array? Something similar to what happens when you `print_r` an array? –  Jan 19 '12 at 15:24
  • was hoping if i had an array such as //$my_array(3,2,1), i could use printf() as follows //printf("Ready! %s,%s,%s Go!",$my_array) to output // Ready! 3,2,1, Go! – Destiny Makuyana Jan 19 '12 at 15:29
  • No, you can't do that... Trust me, you wouldn't want that too. You are a beginner, in few years talk with us, you will see that is not an option. :D – workdreamer Jan 19 '12 at 15:34
  • 1
    [`vprintf()`](http://php.net/vprintf) – salathe Jan 19 '12 at 15:44
  • **seealso:** https://stackoverflow.com/questions/5701985/vsprintf-or-sprintf-with-named-arguments – dreftymac Feb 10 '18 at 00:29
  • [There is a php function to do that](https://stackoverflow.com/a/13325716/2269902) – Hisham Dalal Mar 01 '21 at 19:17

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
  • 8,082
  • 5
  • 43
  • 41
Pateman
  • 2,727
  • 3
  • 28
  • 43
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
  • 761,203
  • 64
  • 569
  • 643
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
  • 34,211
  • 7
  • 53
  • 66
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,836
  • 1
  • 35
  • 37
0

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

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