Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printf() is less reliable than echo in PHP? [closed]

Tags:

php

echo

printf

For some reason, I have adopted using printf($var) over using echo $var. I don't really know why.

However, it seems like if I ever have an issue outputting a string from a variable - if I change printf($var) to echo $var - 90% of the time it fixes the issue.

This has happened to me on more than one occasion with differing errors, anywhere from too few arguments to just echoing a null/blank string.

Can anyone shed some light as to why printf() seems to work less reliably than echo?

like image 246
Xhynk Avatar asked Apr 17 '26 23:04

Xhynk


2 Answers

Short answer, don't use printf($var) unless you specifically need it.

The reason is that $var passed as the first argument is treated as a format string and things like %s and %d, etc. have a special meaning. In C / C++ this can cause segmentation faults, whereas in PHP you get a slap on the wrist in comparison.

The equivalent of echo or print is printf('%s', $var); it casts $var to a string and then outputs it.

Btw, printf() is a function whereas echo and print are language constructs; therefore you're likely to get better performance with echo.

like image 198
Ja͢ck Avatar answered Apr 20 '26 12:04

Ja͢ck


printf — Output a formatted string ,print returns a value. It always returns 1.and what the echo do — Output one or more strings

Always returning 1 doesn't seem useful. And a comma delimited list of arguments can be simulated with string concatenation or multiple calls

The print function is slightly more dynamic than the echo function by returning a value, and the echo function is slightly (very slightly) faster. The printf function inserts dynamic variables/whatever into wherever you want with special delimiters, such as %s, or %d. For example, printf('There is a difference between %s and %s', 'good', 'evil') would return 'There is a difference between good and evil'.

check this PHP: Benchmarking echo vs. print vs. printf

and the result

it appears that echo and print are really, really close in terms of speed. The difference per command was only 2/1,000,000 of a second. It just comes down to personal preference. I use echo because that’s what I used first. The speed drop on print appears to come when you assign a variable, at which point the command speed drops 1/100,000 of a second, which is still fairly minor.

form above link

like image 27
NullPoiиteя Avatar answered Apr 20 '26 12:04

NullPoiиteя



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!