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?
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
yes
On your html place this:
<pre>
<?php
print_r ($your_array);
?>
</pre>
or on your code only place:
print_r ($your_array);
printf does not handle an array recursively. You can however do:
$cars=array('Saab','Volvo','Koenigsegg');
print_r($cars);
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
Are you looking for something like this using print_r with true parameter:
printf("My array is:***
%s***
", print_r($arr, true));