How to format array out with printf in php
Solution 1
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
Solution 2
Are you looking for something like this using print_r with true parameter:
printf("My array is:***\n%s***\n", print_r($arr, true));
Solution 3
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
Destiny Makuyana
I am currently a Software Engineering student in Liverpool, England. Although primarily develop in C# and .NET in university, I enjoy working in Xcode making iOS Apps. I am more heavily involved in Web Development and enjoy working with php, django, jQuery and html5/css3. Please feel free to contact me if need be!
Updated on June 04, 2022Comments
-
Destiny Makuyana almost 2 years
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?