This question might be a duplicate of why in array single quotes not required according to the syntax
but I didn't the explanation I need over there. We know we can do echo "$myArr[0]", but we can't do the same with associative arrays like echo "myAssocArr['myKey']". I know we can use php complex syntax to get around, like echo "{myAssocArr['myKey']}".
My question is, if php can access normal index arrays without complex syntax, then why can't it access accosiative arrays' values as well. What is happening inside php compiler/zend/whatever engine that prevents it from accessing assosiative arrays' values in a string without the complex syntax.
I read the manual on variable parsing.
I don't think there's any reasonable explanation other than that " and ' can be used to start and end a string. However, when you are parsing a string for variables you are already in a string. Those "tokens" are just not allowed in the simple syntax. Encountering a new begin or end of a string would make little sense. You can however use the syntax:
echo "myAssocArr[myKey]";
which avoids this problem. I agree it is not very satisfactory, but other than checking the PHP source code, I don't think you'll get a better answer.
For example:
<?php
$var1 = 'cow';
$var2 = 'lamb';
?>
<?=$var1,$var2?>
or should that last part be:
<?=$var1.$var2?>
The operation you're performing is concatenation. Technically you can also use a comma as well, but for clarity I would use the concatenation operator, which is a period (or dot).
Using a comma seems to be slightly faster, but this kind of speed differences are negligible. Code should always be optimized for reading (it's hard to read by definition already), only when serious performance issues are encountered you can start optimization. And even then, replacing concatenation with passing multiple arguments is not going to improve much.
Also, this works only for the echo() function. Consistency is usually good thing.
P.S. Using a space after a comma or around operators is also often recommended for readability:
<?=$var1 . $var2?>
<?=$var1, $var2?>
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.
I'm merging two different versions of a translations array. The more recent version has a lot of changes, over several thousand lines of code.
To do this, I loaded and evaluated the new file (which uses the same structure and key names), then loaded and evaluated the older version, overwriting the new untranslated values in the array with the values we already have translated.
So far so good!
However, I want to be able to echo out the constructor for this new merged array so I can cut and paste it into the new translation file, and have job done (apart from completing the rest of the translations..).
The code looks like this (lots of different keys, not just index):
$lang["index"]["chart1_label1"] = "Subscribed";
$lang["index"]["chart1_label2"] = "Unsubscribed";
And the old..
$lang["index"]["chart1_label1"] = "Subscrito";
$lang["index"]["chart1_label2"] = "Não subscrito";
After loading the two files, I end up with a merged $lang array, which I then want to echo out in the same form, so it can be used by the project.
However, when I do something like this..
foreach ($lang as $key => $value) {
if (is_array($value)) {
foreach ($value as $key2 => $value2) {
echo "$lang['".$key."']"; // ... etc etc
}
}
}
..obviously I get "ArrayIndex" etc etc instead of "$lang". How to echo out $lang without it being evaluated..? Once this is working, can add in the rest of the brackets etc (I realise they are missing), but just want to make this part work first.
If there's a better way to do this, all ears too!
Thanks.
edit:
What I was really looking for was this:
"Note: Unlike the three other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings."
So no need even to escape. May come in handy one day for someone... about merging the arrays, there's a great recursive array merging function on the PHP manual page for array_merge(), which also came in handy.
Thanks to whoever downvoted! Love you too.
Either escape the $: "\$lang" or use single quotes: '$lang'
Note that you really don't need to post a whole page of backstory, if your entire question just boils down to "how do I output a dollar sign in PHP"
there is var_export() function, but I do not understand the purpose of this terrible mess.
It's all too... manual
why not to use a gettext - an industry standard for multi-language site?
or at least some other format, more reliable than plain PHP one?
Programming code is not intended to be written automatically.
One of Googles Let's make the internet faster talks included something about using echo with multiple arguments in PHP instead of using print or string concatenation.
echo 'The ball is ', $color;
Rather than either of these
echo "The ball is $color";
echo 'The ball is ' . $color;
What if output buffering is in play ?
What would be the difference between using echo with multiple arguments along with output buffering, vs using the alternate methods without output buffering ?
Be sure to read the PHP team's rebuttal of Google's performance tips.
Specifically, he (Gwynne Raskind) says:
4) "Don't use concatenation with echo."
This is exactly the opposite of correct advice. The engine handles
multiple arguments to echo() in such a way that concatenation (or
double-quoted string interpolation) is actually much faster. See the
benchmark posted at http://pastie.org/523020.
the first version should be a bit faster because it doesn't have to parse the string for variable expansion (single quotes) and it doesn't have to spend time concatenating the two strings before writing them. i don't think that buffering will affect this