'Can I write PHP code across multiple lines per statement?
Is it okay to write code like this, with statements spanning across multiple lines?
$db_selected =
mysql_select_db(
'my_dbase',
mysql_connect(
'localhost',
'mysql_user',
'mysql_password'
)
);
In HTML, new lines are ignored, but in PHP I sometimes get errors. I'm not too familiar with PHP, but thought this should be just fine, no?
Solution 1:[1]
No, but not for why you think. The whitespace is fine, but there is an issue with that code:
mysql_select_db(
'my_dbase',
// don't call mysql_connect here!!!
mysql_connect(
'localhost',
'mysql_user',
'mysql_password'
)
);
MySQL connect will return FALSE on error. This means that you'll not be able to handle the mysql_error()
there AND it will cause an error in mysql_select_db
.
You're better off:
$conn = mysql_connect(
'localhost',
'mysql_user',
'mysql_password'
) or die( mysql_error() );
mysql_select_db(
'my_dbase',
$conn // optional parameter, but useful nonetheless.
);
Solution 2:[2]
I'm gonna answer my own question: Simply tried this and on my LAMP server, the originally posted code snippet works just fine (php 5).
So yes, you can separate statements including those with operators into multiple lines.
And the answer with the string concatenation - yes there are myriad answers on this forum already about that but I was asking about statements, not strings, which I could not find answered elsewhere.
Thanks everyone! Especially Geroge Cummins.
Solution 3:[3]
Yes, but for certain things, such as text I do something like ...
$someText = " blah blah blah ".
"some more blah blah blah";
Hope this helps
UPDATE 2022 haha
I know this is super old, but another way would be using EOF
$str = <<<EOF
You can put whatever <p>text</p>. <b>you want to put</b>
in here, for as
many lines as you want ()I)(#*$)#*($)#
EOF;
Solution 4:[4]
Whitespace is generally ignored, so you can insert line breaks as needed. However, you need to end each statement with a semicolon (;
).
Solution 5:[5]
Yes it's okay, as long as there are no new lines after operators, such as =
, in
, ==
, etc...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | cwallenpoole |
Solution 2 | OGHaza |
Solution 3 | |
Solution 4 | George Cummins |
Solution 5 | Shaz |