Why this statement need in php - php

How this statements named in php?
if($a)
$b = "Some";
I often meet in group projects this statement. And I do not like her because I do not understand how it works. So how it work? For example how php know where end this construction, coz {} is empty? When it is advantageous to use:
if($a)
$b = "Some";
Than:
if($a)
{
$b = "Some";
}
Sorry if the question is stupid. But I want to understand why this statement need without {}
Thanks

For single line statements you dont have to provide braces({}).
But for better readability and avoid any error, in case you might need to add multiple statements later, it is recommended to use block statments.
When you omit the braces it will only treat the next statement as body of the condition.
if ($x) echo 'foo';
is the same as
if ($x) { echo 'foo'; }
but remember that
if ($x)
echo 'foo';
echo 'bar';
will always print "bar"
Internally it's the other way around: if will only look at the next expression, but PHP treats everything in {} as a single "grouped" expression.
Same for the other control statements (foreach, and so on)

As mentioned before - its shorthand for a single if statement. Just some more infos:
if($a)
$b = "Some";
is the same as
if($a) {
$b = "Some";
}
But remember that
if($a)
$b = "Some";
$c = "More";
Is similar to
if($a) {
$b = "Some";
}
$c = "More";

The if statement executes the following statement if its condition is true. The following statement can either be a single statement, or it can be a group of statements grouped together with {}. You can use {} even without if, it just won't do much on its own.
// pretty useless, but valid
{
echo 'Foo';
echo 'Bar';
}
// valid, one statement following
if (true) echo 'Baz';
// valid, group of statements following
if (true) {
echo 'Foo';
echo 'Bar';
}

try it and test this code
$b = "testing";
if($b == "testing")
echo "This is if";
echo "This is another if";
echo "This is another";
echo "This is so on";
here I use only if so I don't need to define scope OR write braces in if condition I can use multiple messages, in below code I use else there is also no need to define scope OR braces. But in if there're multiple line of code some you'll confuse about your own code and also other programmers are.
$a = "test";
if($a == "test")
echo "This is if";
else
echo "This is else";
But for example if I create a if statement and it contains one line message in if body like upper code it'll work without any error BUT if I add one more line of code OR message in if body it'll return error
$a = "test";
if($a == "test")
echo "This is if";
echo "This is if 2";
else
echo "This is else";
so I've to use braces for if condition like this
$a = "test";
if($a == "test") {
echo "This is if";
echo "This is if 2";
} else
echo "This is else";
now it'll not return error because I use braces in if condition. Remember one line of code in if body will not return any error but second line of code in if condition will return error. Braces will define the scope of your if body as you can see in the third code I didn't use braces in else because it have one line of code OR message.

You will run into a nightmare of problems if there are multiple if statements. The above (without using braces) does work only for the first set of if statement.
Second thing would be if you add braces {....} , That would add the readability to your code and your code does look organized.

By definition the if statement reads only one statement after it. If you have many statements you should group them as one using {}

Related

Using just if and elseif in a php syntax

This might be a noob question. I just wanna ask if it's correct to use the following codes inside a switch statement:
case 'OPTION1':
if ($_SESSION['session2'] == 'cart') {
$code = '1567';
}
else if($_SESSION['session2'] == 'online') {
$code= 'A90f';
}
break;
Or do I always have to add an else at the end of every if elseif statements? Thank you!
You only need to add an else and as many else ifs as makes sense in the code, so your example is fine.
Sometimes you may want to add some default behaviour (just the same as in a switch()) which covers the - it didn't match anything else...
if ($_SESSION['session2'] == 'cart') {
$code = '1567';
}
else if($_SESSION['session2'] == 'online') {
$code= 'A90f';
}
else {
$code = '';
}
But you could alternativelty say
$code = '';
if ($_SESSION['session2'] == 'cart') {
$code = '1567';
}
else if($_SESSION['session2'] == 'online') {
$code= 'A90f';
}
The OP's question concerns the basics of PHP, a worthwhile subject for review whatever one's expertise may be. While a switch statement may prove useful for avoiding messy looking long if-statements, the OP's code contains a switch statement with only one case that contains itself an if control structure. So, while the syntax is correct, the switch statement appears superfluous since the if control structure could just as easily execute without being embedded in a switch statement.
As far as the usage concerning else, that provides for default code to execute in the case of one or more if-statements evaluating as false. Also, note that the else if code only evaluates when the preceding if condition returns false. To illustrate:
<?php
$a = 3;
$b = 5;
if ($a == $b) {
echo '$a and $b are equivalent';
}
else
if ($a > $b) {
echo '$a is greater than $b';
}
else
{
echo 'The rain in Spain stays mainly in the plain';
}
?>
See live code and read more here
You could optionally recode the preceding example using a switch statement as follows:
<?php
$a = 3;
$b = 5;
switch($a) {
case ($b):
echo '$a and $b are equivalent';
break;
case ($a > $b):
echo '$a is greater than $b';
break;
default:
echo 'The rain in Spain stays mainly in the plain';
break;
}
?>
See live code
With respect to the switch statement the Manual notes:
In many occasions, you may want to compare the same variable (or
expression) with many different values, and execute a different piece
of code depending on which value it equals to. This is exactly what
the switch statement is for.
#Nigel's answer is fine. I'd just add that I'll rather use elseif instead of else if for PSR-2 compliance: https://www.php-fig.org/psr/psr-2/
The behaviour between else if and elseif is just the same.

What is the difference between "{$var1}someString" and "$var1someString"?

I can make out the difference between
echo "{$var1}someString" // here the variable is $var1
echo "$var1someString" // here the variable is $var1someString
The question is why to use {}? It works only with {}. It does not work with (). What is so special about { }?
The curly braces {} are used in that way to identify variables within strings:
echo "{$var1}someString"
If you look at:
echo "$var1someString"
PHP can't possibly determine that you wanted to echo $var1, it's going to take all of it as the variable name.
You could concatenate your variables instead:
echo $var1 . "someString"
It doesn't work for () simply because the PHP designers choose {}.
you expained it yourself. thats simply the syntax php uses for this - nothing more. to quote the documentation:
Complex (curly) syntax
Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$
According to the documentation of string, the curly part is called complex syntax. It basically allows you to use complex expressions inside string.
Example from the documentation:
<?php
// Show all errors
error_reporting(E_ALL);
$great = 'fantastic';
// Won't work, outputs: This is { fantastic}
echo "This is { $great}";
// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";
// Works
echo "This square is {$square->width}00 centimeters broad.";
// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";
// Works
echo "This works: {$arr[4][3]}";
// This is wrong for the same reason as $foo[bar] is wrong outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}";
// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";
// Works.
echo "This works: " . $arr['foo'][3];
echo "This works too: {$obj->values[3]->name}";
echo "This is the value of the var named $name: {${$name}}";
echo "This is the value of the var named by the return value of getName(): {${getName()}}";
echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>
Here {} define that variable within these are not a simple string so php pic up that variable value instead of assuming that as a simple string.

Basic if..elseif...else question in PHP

Sorry, just a very basic question on conditionals in PHP
If {}
elseif {}
else {}
If the if condition comes out to be true, will PHP still evaluate the elseif to see if that is true as well?
No. (Basic answer for a basic question)
You can read about that in depth in the PHP Manual: elseif/else if, the first example is like yours.
Not, it won't. It will just execute the if code, and then continue after the else.
In order to see it, you could check this:
if (true)
{
echo "foo inside if"
}
else if (true)
{
echo "foo inside else if"
}
else
{
echo "foo inside else";
}
echo "\nfoo after else"
The above code will print:
foo inside if
foo after else
and not
foo inside if
foo inside else if
foo after else
Nope! Once a condition is met anywhere in an if/else block, PHP exits that block and moves on. For example, in this code:
if ($a <= 3) {
echo "small";
}
elseif ($a <= 6) {
echo "medium";
}
else {
echo "large";
}
... if $a is 2, it will echo "small" because $a is <= 3, but not "medium", even though $a is also <= 6.
If you did want PHP to check subsequent conditions, you'd use multiple if statements instead. For example:
if ($b < 4) {
echo "less than 4";
}
if ($b < 8) {
echo "less than 8";
}
... would echo both "less than 4" and "less than 8" if $b were, say, 3.
As others have already mentioned, no, it will not even test the elseif condition. This is also important for situations like the following:
$a = 1;
if ($a > 0) { }
else if (++$a > 0) { } // note the increment operator
else { }
echo $a; // produces 1
Any expressions that modify values as a byproduct of the condition test will not fire either.
If the first if is true, the code will enter the if and then execute the code inside of there. Then it will exit past the else and continue on.
No, it won't. After executing the if code, it will continue execution after the else.
Not the case. As soon as the condition you specify is met in a if query, php will stop going forward with the process and will contiue on to the code that appears after the if query has been ended.
No, it won't execute else if statements as the if condition becomes true
This is general truth for if-else-if-else block in all languages
$a=1;
if($a==1){
echo "inside if";
}else if($a==2){
echo "inside else if";
}else{
echo "inside else";
}
It will have output as below:
inside if
As the value of a is 1 it won't execute else if and else block
Hope it Helps!!!!

How should boolean expressions be written in PHP?

How should the following boolean expression be written in PHP:
$foo = "";
if($var==TRUE){
$foo = "bar";
}
or
if($var==TRUE){
$foo = "bar";
}else{
$foo = "";
}
or
$foo = ($var==TRUE) ? "bar": "";
First off, true is not a constant, it's a token, so please don't uppercase it (I know some standards do that, but I think it confuses the meaning)...
Second, you don't need the redundant $var == true comparison inside the if. It's exactly the same as if ($var) { (For a double == comparison. An identical comparison === would need to be explicit).
Third, I prefer the pre-initialization. So:
$foo = '';
if ($var) {
$foo = 'one status';
} else {
$foo = 'another status';
}
If you don't need the else branch, just remove it. I prefer the pre-initialization since it forces you to initialize the variable, and it prevents cases where you forget to initialize it in one of the branches. Plus, it gives you a type hint when you go back to read the function later...
And for a simple branch like that, using the ternary syntax is fine. If there's more complex logic, I'd stay away though:
$foo = $var ? 'bar' : '';
All of those work. It's preference. I'd consider initializing the variable first like you do in the 1st example. But for something this simple, the 3rd option is fine in my book.
Also, the 3rd doesn't have to be so verbose if $var is just a boolean value:
$foo = $var ? "bar" : "";
I like the first one:
$foo = "";
if($var==TRUE){
$foo = "bar";
}
Since it is clear, concise, and easy to read.
I prefer the first one (except for the redundant test for the boolean) because it works consistently across languages, particularly those requiring to declare the variable (and maybe typify it) ahead of setting it.
Java:
String foo = "";
if (var) {
foo = "Something";
}
JavaScript or JavaFX:
var foo = "";
if (var) {
foo = "Something";
}
Etc.
One can use the 3rd form too but if the condition (or assignment) is complex, it is a bit less readable.
Doesn't matter very much. I like the first one when there's a lot of elseif's so that you know the variable is always initialized. But it's really just a matter of preference.
Like the quotes, I like using single ones in php. No good reason :)
The right answer, as it often is the case is, "it depends". In this case,
if ($var==TRUE) $foo = "bar";
else $foo = "";
is very clear. But what is your context?
In general, the tertiary operator, your third option, should be used with extreme caution, as it very easily becomes hard to read.
But think in terms of what you want your code to MEAN, more than about what it DOES. Do you want to set your $foo to a "normal" value and then override it? Or do you want to set to something that depends on what $var is?
Something I find useful to change, that is not directly what you ask, but that is similar, is this, from
function func() {
...
if ($condition) {
do plenty
of things
}
else {
do plenty
of things
}
}
That, I generally like to change to:
function func() {
...
if ($condition) {
do plenty
of things
return;
}
do plenty
of things
}
It generally makes sense.
Just ask yourself: "If someone who didn't know anything about my code read it, would it make sense to him? Or her?"

Curly braces in string in PHP

What is the meaning of { } (curly braces) in string literals in PHP?
This is the complex (curly) syntax for string interpolation. From the manual:
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because
it allows for the use of complex expressions.
Any scalar variable, array element or object property with a string
representation can be included via this syntax. Simply write the
expression the same way as it would appear outside the string, and
then wrap it in { and }. Since { can not be escaped, this syntax
will only be recognised when the $ immediately follows the {. Use
{\$ to get a literal {$. Some examples to make it clear:
<?php
// Show all errors
error_reporting(E_ALL);
$great = 'fantastic';
// Won't work, outputs: This is { fantastic}
echo "This is { $great}";
// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";
// Works
echo "This square is {$square->width}00 centimeters broad.";
// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";
// Works
echo "This works: {$arr[4][3]}";
// This is wrong for the same reason as $foo[bar] is wrong outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}";
// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";
// Works.
echo "This works: " . $arr['foo'][3];
echo "This works too: {$obj->values[3]->name}";
echo "This is the value of the var named $name: {${$name}}";
echo "This is the value of the var named by the return value of getName(): {${getName()}}";
echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>
Often, this syntax is unnecessary. For example, this:
$a = 'abcd';
$out = "$a $a"; // "abcd abcd";
behaves exactly the same as this:
$out = "{$a} {$a}"; // same
So the curly braces are unnecessary. But this:
$out = "$aefgh";
will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:
$out = "${a}efgh"; // or
$out = "{$a}efgh";
As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner. Remember to use double quotes (" ") as their content is parsed by PHP, because in single quotes (' ') you'll get the literal name of variable provided:
<?php
$a = '12345';
// This works:
echo "qwe{$a}rty"; // qwe12345rty, using braces
echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used
// Does not work:
echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
echo "qwe$arty"; // qwe, because $a became $arty, which is undefined
?>
Example:
$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";
Without curly braces PHP would try to find a variable named $numberth, that doesn't exist!
I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.
$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
$this->{'value_'.$period}=1;
}
This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.
You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.
class timevalues
{
// Database table values:
public $value_hour; // maps to values.value_hour
public $value_day; // maps to values.value_day
public $value_month; // maps to values.value_month
public $values=array();
public function __construct()
{
$this->value_hour=0;
$this->value_day=0;
$this->value_month=0;
$this->values=array(
'hour'=>$this->value_hour,
'day'=>$this->value_day,
'month'=>$this->value_month,
);
}
}

Categories