This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Please help me with this issue. I am trying to echo out 7 or 8 input types.
The input types must have 2 values from my database.
The Arrays are called : $adressX[] and $adressY. and are automatically loaded when the webpage loads.
So when number is 0 , i want to create a input type with the value : ($adressX[0],$adressY[0]).
I keep getting parsing errors , this being my first project on php/javascript.
Please help me.
My code is like this.
<?php
for ($number=0;$number<=$array_no-1 ;$number++)
{
echo '<input type="text" id="inputtype"."$number"
value="".$adressX['.$number'],".$adressY['.$number']">';
};
?>
You were messing up your quotes and periods. Try this:
<?php
for ($number = 0; $number <= $array_no-1; $number++) {
echo '<input type="text" id="inputtype' . $number . '" value="' . $adressX[$number] . ',' . $adressY[$number].'" />';
}
?>
You should read up on how PHP handles quotes and concatenation, but here are a few examples to get you started.
If you want to start the string with a single quote, you must end/concatenate the string with a single quote as well. Like this:
$var = 'yay';
$string = 'The value of the variable is ' . $var;
$string2 = 'The value of the variable is ' . $var . '!'; // Add another string after variable
Similarly, if you start with double quotes, you have to end/concatenate with double quotes, like this:
$var = "yay";
$string = "The value of the variable is " . $var;
$string2 = "The value of the variable is " . $var . "!";
$string3 = "The value of the variable is $var!";
Notice the last example, $string3. When using double quotes, you can put variables inside the quotes and PHP will still parse them; however, I don't condone this and I ALWAYS concatenate so when using an IDE with syntax highlighting it is obvious where the variables are.
Here is an example of putting the same type quotes in the string that you start/end the string with. To do this, you must use a slash () to tell PHP that these should be parsed as regular quotes instead of delimiters.
$string = 'You\'re using escaped quotes now!'; // notice the \ in front of the ' in you're
Lastly, here is an example of an HTML string in PHP. I usually start these strings with single quotes so that I can use the conventional double quote delimiters for the HTML.
$html = '<div class="someClass">Hello world!</div>';
<?php
for ($number=0;$number<=$array_no-1 ;$number++) {
echo '<input type="text" id="inputtype'.$number'" value="'.$adressX[$number].','.$adressY[$number].'">';
}
Using PHP's echo and print statements is usually where new PHP programmers go to for getting output to the screen. However, when dealing with the output of HTML markup, escaping out of quotes and syntax problems can creep up really quickly. Instead, try using sprintf to format these more complicated markup elements. Here's an example.
for ( $number = 0; $number <= $array_no - 1; $number++ )
{
echo sprintf( '<input type="text" id="inputtype%u" value="%s,%s"/>', $number, $addressX[ $number ], $addressY[ $number ] );
}
The essential things to know is that, at it's essence, sprintf is a complicated kind of search and replace with formatting method. The first argument is a string with placeholders and all of the following arguments are the variables that will be used in that string to replace the placeholders. The number of parameters that follow the input string must match the number of placeholders in your string.
You'll notice %s and %u in the input string that's used in my example. Those mean format as a %s String or as an %u Integer. There are a LOT more ways for format stuff, but, as a novice, these are the ones you'll probably find yourself using the most.
How is this any easier?
It's easier because you can us a properly formatted HTML snippet with double quotes and just add in placeholders. Visually, I find it much more easy to read than a ton of ' . $variable . ' bits scattered throughout your code.
Besides, sprintf is going to become something you use regularly as you move up the PHP ladder. Time to learn it.
Related
I am wondering, What is the proper way for inserting PHP variables into a string?
This way:
echo "Welcome ".$name."!"
Or this way:
echo "Welcome $name!"
Both of these methods work in my PHP v5.3.5. The latter is shorter and simpler but I'm not sure if the first is better formatting or accepted as more proper.
Between those two syntaxes, you should really choose the one you prefer :-)
Personally, I would go with your second solution in such a case (Variable interpolation), which I find easier to both write and read.
The result will be the same; and even if there are performance implications, those won't matter 1.
As a sidenote, so my answer is a bit more complete: the day you'll want to do something like this:
echo "Welcome $names!";
PHP will interpret your code as if you were trying to use the $names variable -- which doesn't exist.
- note that it will only work if you use "" not '' for your string.
That day, you'll need to use {}:
echo "Welcome {$name}s!"
No need to fallback to concatenations.
Also note that your first syntax:
echo "Welcome ".$name."!";
Could probably be optimized, avoiding concatenations, using:
echo "Welcome ", $name, "!";
(But, as I said earlier, this doesn't matter much...)
1 - Unless you are doing hundreds of thousands of concatenations vs interpolations -- and it's probably not quite the case.
Double-quoted strings are more elegant because you don't have to break up your string every time you need to insert a variable (like you must do with single-quoted strings).
However, if you need to insert the return value of a function, this cannot be inserted into a double-quoted string--even if you surround it with braces!
//syntax error!!
//$s = "Hello {trim($world)}!"
//the only option
$s = "Hello " . trim($world) . "!";
Since php4 you can use a string formater:
$num = 5;
$word = 'banana';
$format = 'can you say %d times the word %s';
echo sprintf($format, $num, $word);
Source: sprintf()
I prefer this all the time and found it much easier.
echo "Welcome {$name}!"
From the point of view of making thinks simple, readable, consistent and easy to understand (since performance doesn't matter here):
Using embedded vars in double quotes can lead to complex and confusing situations when you want to embed object properties, multidimentional arrays etc.
That is, generally when reading embedded vars, you cannot be instantly 100% sure of the final behavior of what you are reading.
You frequently need add crutches such as {} and \, which IMO adds confusion and makes concatenation readability nearly equivalent, if not better.
As soon as you need to wrap a function call around the var, for example htmlspecialchars($var), you have to switch to concatenation.
AFAIK, you cannot embed constants.
In some specific cases, "double quotes with vars embedding" can be useful, but generally speaking, I would go for concatenation (using single or double quotes when convenient)
I know this question already has a chosen answer, but I found this article that evidently shows that string interpolation works faster than concatenation. It might be helpful for those who are still in doubt.
Either one is fine. Use the one that has better visibility for you. And speaking of visibility you can also check out printf.
I use a dot(.) to concate string and variable. like this-
echo "Hello ".$var;
Sometimes, I use curly braces to concate string and variable that looks like this-
echo "Hello {$var}";
Do not concatenate. It's not needed, us commas as echo can take multiple parameters
echo "Welcome ", $name, "!";
Regarding using single or double quotes the difference is negligible, you can do tests with large numbers of strings to test for yourself.
Go with the first and use single quotes!
It's easier to read, meaning other programmers will know what's happening
It works slightly faster, the way opcodes are created when PHP dissects your source code, it's basically gonna do that anyway, so give it a helping hand!
If you also use single quotes instead of double quotes you'll boost your performance even more.
The only situations when you should use double quotes, is when you need \r, \n, \t!
The overhead is just not worth it to use it in any other case.
You should also check PHP variable concatenation, phpbench.com for some benchmarks on different methods of doing things.
It only matter of taste.
Use whatever you wish.
Most of time I am using second one but it depends.
Let me suggest you also to get yourself a good editor which will highlight a variable inside of a string
You Should choose the first one. They have no difference except the performance the first one will be the fast in the comparison of second one.
If the variable inside the double quote PHP take time to parse variable.
Check out this Single quotes or double quotes for variable concatenation?
This is another example Is there a performance benefit single quote vs double quote in php?
I did not understand why this answer in above link get upvoted and why this answer got downvote.
As I said same thing.
You can look at here as well
What is faster in PHP, single or double quotes?
I know this is an old question, but I think someone has to mention all pros & cons:
Better Syntax: That's personal preference.
Performance: No difference. As many mentioned, double-quote might be faster if using unrealistically many variables.
Better Usage: Single quote (mostly). As #Khez said, with single quote you can concatenate anything, even function calls and variable modification, like so: echo 'hi ' . trim($name) . ($i + 1);. The only thing double-quote can do that single-quote cannot do is usage of \n, \r, \t and alike.
Readability: No difference (may personal preference apply).
Writability/Re-Writability/Debugging: In 1-line statements there is no difference, but when dealing with multiple lines, it's easier to comment/uncomment lines while debugging or writing. For example:
$q = 'SELECT ' .
't1.col1 ' .
',t2.col2 ' .
//',t3.col3 ' .
'FROM tbl1 AS t1 ' .
'LEFT JOIN tbl2 AS t2 ON t2.col2 = t1.col1 ' .
//'LEFT JOIN tbl3 AS t3 ON t3.col3 = t2.col2 ' .
'WHERE t1.col1 = ' . $x . ' ' .
' AND t2.col2 = ' . $y . ' ' .
//' AND t3.col3 = ' . $z . ' ' .
'ORDER BY t1.col1 ASC ' .
'LIMIT 10';
Less Escaping: Single-quote. For single quote you need to escape 2 characters only (' and \). For double quote you need to escape 2 characters (", \) and 3 more if required ($, { and }).
Less Changes: Single quote. For example if you have the following code:
echo 'Number ' . $i . '!';
And you need to increment 1 to $i, so it becomes likes:
echo 'Number ' . ($i + 1) . '!';
But for double quote, you will need to change this:
echo "Number $i!";
to this:
echo "Number " . ($i + 1) . "!";
Conclusion: Use what you prefer.
If you want to execute a SQL command and your variables are array members, then you should not use single quotes inside [] of array (like this: ['']); for example if you use this string as a SQL command, you get server error 500:
$con = mysqli_connect('ServerName', 'dbUsername', 'dbPassword');
mysqli_select_db($con, 'dbName')
//'ID' is auto increment field.
$sql = "INSERT INTO sampleTable (ID, TraceNo) VALUES ('','$sampleArray['TraceNo']')";
mysqli_query($con, $sql)
The correct string is:
//'ID' is auto increment field.
$sql = "INSERT INTO sampleTable (ID, TraceNo) VALUES ('','$sampleArray[TraceNo]')";
echo "Welcome $name!";
This is the best way.
You don't need to anything else
So, I am just familiarizing myself with php and I see that there are few alternative formats when it comes to writing in php.
What I am confused about is the "dots" or their placements as well other stuffs such as "_".
For example,
<?php
if(!empty($my_post))
{
echo $my_post . ' ' . __('my_post','my_site') . ' + ';
}
?>
It might be a really silly question but could someone explain to me what the function of "dots" in between and just the format itself.
Thanks!
TheSaurus has answered it right. Dots(.) in PHP are the concatenation operators like that plus(+) in java. Whenever you want to build a string with some sub strings, you may use it. There are several other plenty of uses of this, depending on the use.Like One explained in above example.
e.g.:
$line="STACK OVERFLOW";
echo "$line<br/>"
// Some Computation
$line.="is good"; // Here used to concatenate
echo $line
This will output
STACK OVERFLOW
STACK OVERFLOW is good
The dot is the concatenation operator ('.'), which returns the concatenation of its right and left arguments.
<?php
$var = "hello";
$world = "world";
echo "$var" . '$world'; //outputs hello$world
echo "$var" . "$world"; //outputs helloworld
echo "$var" . $world; //outputs helloworld
?>
Read More
The dot
As many have answered before, the dot concatenates strings into a single string. But it's not necessary for bot to be strings. You can concatenate an integer with a string just fine.
<?php
$a = 'Number';
$b = 2;
$c = 'Yay!';
echo $a . $b . $c; // Output: Number2Yay!
?>
The double underscore
In your case, the __() function is just an alias for gettext(): documentation: LINK
Usually, though, the double underscore is used for Magic Methods.
You'll find this piece of text in the documentation:
PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.
You can read all about them here: Magic Methods
P.S. You'll probably find THIS LINK very useful for future reference. I really recommend looking through this list :)
Dots are string concatenation operators in PHP.
So, if I write
$a="3";
$b="text";
echo $a.$b;
The result will be 3text.
If you want to add some space between those;
echo $a.' '.$b;
The result will be 3 text.
Please note that ' ' means space character in string form.
Also, please check other questions before submitting one.
This question already has answers here:
How can I replace a variable in a string with the value in PHP?
(13 answers)
Closed 8 years ago.
The only way I've found to interpolate a string (that is, expand the variables inside it) is the following:
$str = 'This is a $a';
$a = 'test';
echo eval('return "' . $str . '";');
Keep in mind that in a real-life scenario, the strings are created in different places, so I can't just replace 's with "s.
Is there a better way for expanding a single-quoted string without the use of eval()? I'm looking for something that PHP itself provides.
Please note: Using strtr() is just like using something like sprintf(). My question is different than the question linked to in the possible duplicate section of this question, since I am letting the string control how (that is, through what function calls or property accessors) it wants to obtain the content.
There are more mechanisms than PHP string literal syntax to replace placeholders in strings! A pretty common one is sprintf:
$str = 'This is a %s';
$a = 'test';
echo sprintf($str, $a);
http://php.net/sprintf
There are a ton of other more or less specialised templating languages. Pick the one you like best.
Have you heard of strtr()?
It serves this very purpose and is very useful to create dynamic HTML content containing information from a database, for example.
Given the following string:
$str = 'here is some text to greet user {zUserName}';
then you can parse it using strtr():
$userName = 'Mike';
$parsed = strtr($str,array('{zUserName}'=>$userName));
echo $parsed; // outputs: 'here is some text to greet user Mike'
While sprintf is faster in some regards, strtr allows you to control what goes where in a more friendly way (sprintf is not really manageable on very long strings containing, say, a hundred placeholders to be replaced).
Here is a possible solution. I am not sure in your particular scenario if this would work for you, but it would definitely cut out the need for so many single and double quotes.
<?php
class a {
function b() {
return "World";
}
}
$c = new a;
echo eval('Hello {$c->b()}.');
?>
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm pulling an id number from a database where it is stored as 12345
When I display it on my page (php), I'd like to have it show up as 1-2345
Can I do this without using Javascript? If so, how?
Thanks!
ETA: it's part of a loop of data that is pulled dynamically, so the number is always different. I need to be able to tell it to put a dash after the first number. It's not necessarily 1-2345; it's more X-XXXX (where X is a random number).
You should be able to use the following in MySQL:
select
concat(left(yourCol, 1),
'-',
right(yourcol, length(yourCol)-1)) YourValue
from yourtable
See SQL Fiddle with Demo
This implements the following MySQL functions:
CONCAT
LEFT
RIGHT
LENGTH
Or you can use SUBSTR instead of RIGHT and LENGTH:
select
concat(left(yourCol, 1),
'-',
substr(yourcol, 2)) YourValue
from yourtable;
See SQL Fiddle with Demo
SUBSTR
In PHP
$id = (str)$dbVal;
$str = $id[0]."-".substr($id, 1, strlen($id) - 1);
echo $str;
$var = "12345";
echo $var[0] . "-" . substr($var,1);
This should work for values of any length.
First, use your SELECT MySQL command to find your ID number.
Let's say $string is actually the 'stringified' version of the ID.
$string = "12345";
$string = str_replace($string[0], $string[0] . "-", $string);
echo $string;
The other answers don't address where to put your code, and why. Inserting a dash after the first digit is display-related logic, and display-related logic belongs in the template. It certainly doesn't belong in the database layer. You could put the actual code right alongside the HTML, but that would be a) probably not very intent-revealing and b) not very reusable.
For the best separation of concerns, I would first define a "helper" function like this, in its own file:
function insert_dash_after_first_number($value)
{
return str_replace($value[0], $value[0].'-', $value);
}
Then, in your template, you can do this (granted you included the helper file):
<?php echo insert_dash_after_first_number('12345'); ?>
Hopefully you can see that separating things in this way would make it pretty clear to others and your future self what's going on. You can just look at the function name and see "oh, this inserts a dash after the first number". You don't have to look at any code and think about what it might do.
$string1 = substr($id, 0,1);
$string2 = substr($id, 1, strlen($id));
This might be a silly question but it struck me, and here i ask.
<?php
$x="Hi";
$y=" There";
$z = $x.$y;
$a = "$x$y";
echo "$z"."<br />"."$a";
?>
$z uses the traditional concatenation operator provided by php and concatenates, conversely $a doesn't,
My questions:
by not using the concatenation operator, does it effect the performance?
If it doesn't why at all have the concatenation operator.
Why have 2 modes of implementation when one does the work?
Only slightly, since PHP has to parse the entire string looking for variables, while with concatenation, it just slaps the two variables together. So there's a tiny performance hit, but it's not noticeable for most things.
It's a lot easier to concatenate variables like $_SERVER['DOCUMENT_ROOT'] using the concatenation operator (with quotes, you have to surround the variable in brackets or remove the single quotes in the array index; plus it just makes the string look all ugly). Plus, the concatenation operator allows more flexibility for formatting. For example, you can break up a long string literal onto multiple lines and then concatenate the different parts of it:
$blah = "This is a really really long string. I don't even know how " .
"long it is, but it's really long. Like, longer than an eel " .
"or even a boa constrictor. Wow.";
You can also use the concatenation operator to directly include return values from functions in a string literal (you can't include a function call in a double-quoted string), like this:
$blah = "This has a " . fn_call() . " result, which can't go in the quotes.";
I'm not sure I entirely understand what you're asking here, but I can say that PHP borrows a lot of things from Perl, and one of Perl's mantras is "There's more than one way to do it."
a. Yes. PHP has to parse the string for variables.
b. Because of lines like: echo 'Your Ip address is' . get_ip() . '.';
For reasons A and B.
In some cases your write less with:
$someLongVarName ="Hi";
$someLongVarName .=" there";
VS
$someLongVarName ="Hi";
$someLongVarName = "$someLongVarName there";
Addressing your last question:
Every language has multiple was of doing the same thing. Flexibility is important in every language since any given method may be better the another from situation to situation. The only thing that you should worry about in regards to this is to be consistent in your own code.