Any reason why someone would use printf() for pretty much everything? - php

I am taking over a project from an existing programmer who, to be honest, left the project in a massive heap of unmaintainable, unreadable mess (edit/clarification: dozens upon dozens of standalone .php pages that are a soup of php/html/css that all reference one giant 1500 line 'functions.php' file, ack)
That being said, it seems that pretty much everywhere there is a variable, array, etc. he used printf().
For example, instead of using:
foreach($thing as $t) {
echo "<option value='".$t."'>".$t."</option>";
}
He would use something like:
foreach($thing as $t) {
printf("<option value='%s'>%s</option>", $t, $t);
}
Does anyone have any insight as to why exactly he would do this? Is there some unknown benefit that I am not aware of by using printf() instead of echo/print?
Please note that this isn't just for values that might need to be validated/scrubbed, but for EVERYTHING. Data pulled from the database, random variables and arrays that were defined elsewhere, absolutely everything is printf() instead of just echo or print, and i'm trying to figure out why he would use this method as it might help me understand the logic behind some of the things he built.

"The only reason to use printf() in preference over echo or print() is if you will be using the format string place-holders feature with additional arguments (one for each such place-holder). If not, then print() will be faster, and echo even (very slightly) faster since it does not generate a return value."
Found here: echo VS printf

I imagine he did it for code read-ability. I think using printf/sprintf is more readable than
embedding variables directly into string and alternating '"""''""''".
Personally I think this is the most readable method:
<?php foreach($thing as $t): ?>
<option value="<?php echo $t ?>"><?php echo $t ?></option>
<?php endforeach; ?>
It has the added benefit of looking nice in most IDEs

Well i would have definitely used printf in your example. I often use printf, sprintf, or strtr when outputting html elements with a lot of attributes or complex ones. Its just more readable and its much easier to swap out the values later.

Related

Shorthand For Loop in PHP

I have three-rows code:
echo '<div>';
for ($i=1; $i<=4; $i++) echo $i;
echo '</div>';
Is there any syntax or function let me rewrite above code in only ONE row, for example:
echo '<div>'.(for...).'</div>'; //error
Thanks
Yes its possible, no you dont want to do it:
echo '<div>' . implode('', array_keys(array_fill(1,4,0))) . '</div>';
While readability is completely personal opinion, there are "common" methods, guidelines, and coding standards which are used by a lot of developers.
And while you don't need to adhere to them, it is always up to you or the company you work for, some of these "ways" are just common sense regardless of your personal choice.
Even if there was a way to do it, why would you want to?
How far do you want to go mixing things together for supposed readability?
echo and a loop are completely different things, and should remain separate.
Answer
In answer to your question, no, it is not possible because PHP needs to differentiate between different "things" - functions, echo statements, variable declaration and usage, etc.
The only things you can "mix" are things which PHP allows to be together, like having a variable in a function parenthesis (function($someVar)).
The only thing you could do (and again this has no point, but your choice) is to put it all on one line, like so:
echo '<div>'; for ($i=1; $i<=4; $i++) { echo $i; } echo '</div>';
But that looks terrible.
I want to quickly see different things - "ah an echo, it prints out XYZ", then I want to see a loop separately so I can see easily what the loop is doing.

What is the purpose of the printf() function in PHP?

This may seem like a really daft question, but what is the reason for the existence of the printf() function in PHP?
It seems to me that that using echo will achieve the exact same results, with the added bonus that you don't get confused if you have several variables being output on one line (true, you can use %1$s as opposed to just %s, but it can still get messey with a few variables all being declared).
I know you can also define the type of the variable, without the need to amend it before outputting the string, but to me that doesn't seem like enough to warrent creating a function.
Maybe I'm wrong, maybe I'm missing something obvious, but if someone can help me to understand why it exists (so that I know whether or not I should really be using it!) I'd appriciate it. Thanks.
echo is language construct, printf is a function. It means that so you won't be able to use echo in the same way as printf.
IT'S NOT JUST PERSONAL TASTE
Take a look to the manual pages for both functions:
echo: http://php.net/manual/en/function.echo.php
printf: http://php.net/manual/en/function.printf.php
This topic is discussed there, for example, you cannot call echo with variable functions. Moreover the way they get and manage the input is different. If you do not need the parameters FORMATTING provided by printf you should use echo (it's slightly faster).
Examples
I insist again on some keywords: formatting and function.
The use of printf isn't to concatenate strings or to build a string from placeholders but to do it with custom formatting (possibly from configuration, user inputs or whatever else).
I write some code to explain what I mean (original source in the links I posted).
This code is not valid, echo is not a function so it won't return the printed value (you may use print or sprintf for this but print does not provide string concatenation).
($some_var) ? echo 'true' : echo 'false';
Following code prints a formatted string, in this case the format comes from a literal variable but it may comes from (for example) a GET request or whatever else. Can you rewrite it with echo and the formatting string taken from the configuration?
%format = "%'.-15.15s%'.6.6s\n";
printf($format, $heading1, $value1);
printf() is a port of C's printf() function, so people who got a background writing C code are more familiar with the syntax and will prefer it.
However, most people who start with PHP find it rather confusing.
For comparison:
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
(I used sprintf(), which is the same as printf but it won't actually print the string, it just returns it)
$query = "SELECT * FROM users WHERE user='" . mysql_real_escape_string($user) . "' AND password='" . mysql_real_escape_string($password) . "'";
It's just a matter of preference!
This is about separating static string and formatting, and data.
This separation is encouraged in every programming language that I know of because:
intent of programmer is clearer and enforced
intent is clear: When you read this you know what type is awaited for each field:
printf("a: %.2f, b: %s, c: %d", $a, $b, $c)
intent is enforced: silly type errors are limited (as for the security concerns).
it's more secure
Because it limits silly injection of unexpected meta-strings:
$avg = 3.1415;
// $avg = '3</td>pawned!';
printf("average: %.2f", $avg);
It's much worse in SQL...
usually much easier to read
Appart than you have more clues to the intent of the writer, the string
is clearly in one unique clear block. Data are cleanly listed one by one
after. You don't overuse things like ", . all over the place.
it's very powerfull
I'm curious to see how you would do the following without printf:
printf("%.2f %5d", $v1, $v2);
it's some sort of standard of programming
A lot of other programming languages (C, C++, Java, Python, Bash...) will have
similar printf format and way to treat strings.
So its good for you to know it, and for those who already know, it's easier.
And as a consequence there are plenty of docs and tutorials everywhere on the
subject, and a wikipedia page for it: print format string
The strings can be separated from your data automatically
And this means it's available for translation or syntax correction.
You'll find similar concerns with:
prepared statements in mysql that are now enforced with mysql_query being
deprecated in php 5.5 in favor for prepared statements.
All templating language: where you have the template usually in a different langage,
and the data the other side to render the template.
The more general topic is covered on wikipedia: string interpolation
A last precision:
echo does nothing more than outputing a string. And printf does string interpolation, and outputs a string.
So to be fair, we are here comparing building string via string concatenation vs string interpolation. As there's nothing wrong to output a string with echo. So this is not about echo but how you make your string. You are doing string interpolation even when using echo like this:
echo sprintf("avg: %.3f", $avg);
But then, well there are no more difference between this last form and:
printf("avg: %.3f", $avg);
printf probably exists because PHP was created in C, and printf is traditionally used to output formatted strings in C. printf can actually do a lot more than echo because it can output variables in a variety of formats including decimals to certain places and probably a lot more.
That being said, you can do anything that printf can do with some combination of PHP functions, and it may make more sense depending upon your background.
I'll just explain what I did so you get a clear difference, I'm not a PHP Pro, so maybe I'm wrong and there is a better or easier approach, and also my example may be not so useful to you as well.
I pass each string I want to translate to a function, and it returns the translated string, based on source string and current language, this way it would translate:
"The cat has %d kittens." (english) <=> "Katua %d kume ditu." (euskera)
The fact is that the splitted string for the echo couldn't be translated, as the part previous to the number is not the same for every language, so it must be translated as a "single entity".
It's legacy from C inherited by the PHP language
function http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/
printf takes input differently: you can provide a format string and then list all the required input (just like in C/C++).
'echo' and 'print' only take strings and are easier to use.
Your wish, Your style :)
NOT THAT:
as Others have said echo is a language construct and printf is a real function,
You can do lot with printf.
People coming from C/C++ background know a lot of format strings like %f, %d, %.2f and what not !!!!!
They would prefer printf to echo for this scenario as these floating point precison format and others will be at their finger-tips.
They wd prefer these over PHP's inbuilt format functions.

What would be the use of a gettext_noop function in PHP?

My question is about gettext itself, i kinda don't see the use of a gettext_noop function. I know what it does, but what are the benefits?
If i mark a text with e.g. gettext_noop(), it will not be translated, but xgettext can recognize it, and translation takes place when i output the string as a variable.
Is this because memory usage, or what? Is it better to use it in PHP, or just use _() (or gettext())?
The Gettext manual covers nicely the way gettext_noop may be useful when programming in C.
In PHP, however, it doesn't seem to make sense to do:
$options = array( gettext_noop("one string"),
gettext_noop("another string") ,);
echo _($options[0]);
It should be perfectly ok to do:
$options = array( _("one string") ,
_("another string"), );
echo $options[0];
Since PHP is a dynamically typed language, we'd need to be a lot more creative to find a good use for gettext_noop. Most likely, you won't need it in PHP.
That's probably the reason gettext_noop doesn't exist in a vanilla installation and doesn't even figure in PHP's manual.
A use-case for gettext_noop
It can be useful in certain situations. For instance, let's say you've got an array of allowed values for a drop-down in a form:
$allowed_values = ["red", "orange", "blue"];
In the form, you want the user to see the translated values, but for the request to submit the untranslated values:
<select name="color">
<?php foreach ($allowed_values as $allowed_value) : ?>
<option value="<?= htmlspecialchars($allowed_value) ?>">
<?= htmlspecialchars(_($allowed_value)) ?>
</option>
<?php endforeach ?>
</select>
Unfortunately, xgettext can't find the translatable strings, because they haven't been marked. You can mark them like this:
$allowed_values = [_("red"), _("orange"), _("blue")];
But now you can't retrieve the untranslated values later.
Instead, you could do:
$allowed_values = [gettext_noop("red"), gettext_noop("orange"), gettext_noop("blue")];
Now everything can work as intended, as long as you implement the rest of this answer.
How to implement gettext_noop
PHP doesn't actually include gettext_noop by default. To implement it yourself, add this PHP:
function gettext_noop($string)
{
return $string;
}
And in your invocation of xgettext on the command-line, include this --keyword argument:
xgettext --keyword=gettext_noop ...

php - Most frequent element in array?

This is the function:
function mostFrequent($x) {
$counted = array_count_values($x);
arsort($counted);
return(key($counted));
}
This is the call in the tag:
<?php
$x=mostFrequent(array('cheese','wine','cheese','bread','cheese','bread'));
echo "$x";
?>
This should work right? Also, how do I avoid having to use the temp $x for the echo and just echo the result of the function call directly?
Your solution seems reasonable.
<?php
echo mostFrequent(array('cheese','wine','cheese','bread','cheese','bread'));
?>
echo mostFrequent(array('cheese','wine','cheese','bread','cheese','bread'));
however, it seems wrong way and using a "temp" variable would be better.
Eventually you will learn that it is better to separate business logic from presentation logic.
So, the business of your business logic turns out to be exactly collecting these "temp" variables for the later use in the presentation logic.
also note that variables in PHP require no quotes to address. you are confusing them with strings.
echo $x;
is the proper syntax.

Php: what's the difference between while...endwhile; and while { // stuff here }

What's the difference between
while (expression):
// do stuff
endwhile;
and
while {
}
There is no functional difference.
In practical use I find that:
while (expression):
// do stuff
endwhile;
Is more readable for the designers when you are embedding php code within html. IE:
<? while ($cssClass = array_pop($array)): ?>
<li class="<?=$cssClass?>">
<? endwhile; ?>
Whereas:
while {
}
Is more readable within a php code block.
There's no difference, it comes down to personal preference.
The difference is negligible when the code is actually run, but when coding I find that typing the brackets is (1): quicker, (2): more conventional, and (3): allows for less chance of error (endwhle anyone?).
As a bonus, the editor I use auto-formats the while loops (with brackets, by default) and down the road, if anything is off, the built-in bracket-matching function will catch it.
There's no real difference when writing code.
There can be a difference in levels of convenience in very special circumstances. For example, suppose you are writing a template engine that converts template code to native PHP code which is then cached and executed directly for speed.
In this case, the fact that while...endwhile; avoids using braces may allow you to simplify your parsing algorithm if e.g. it recognizes variables that should be substituted with a syntax like {$var}, which also uses braces.
Of course this is a pretty small benefit in a really extraordinary situation, but you take what you can. :)

Categories