Im new to PHP, and I am learning about control structures. I just learned about if statements, switch statement and while loops. I know the syntax for an if statement is:
if (condition)
{
//code to be executed if the condition is true;
}
switch syntax:
switch (expression)
{
case 1:
//code to be executed;
break;
case 2:
//code to be executed;
break;
default:
//code to be executed;
}
and the syntax for a while loop is:
while (expression)
{
//code to be executed if the expression is true;
}
I see the terms condition and argument and expression pretty interchangeably. Do they all mean the same thing? If not what are the differences?
The condition is an expression which will be evaluated as a boolean. If it evaluates as true, the code is executed, if it evaluates as false the code is skipped.
Arguments are just parameters for functions usually, I also don't see the term in your code samples.
Also be sure to end all cases in a switch statement with a break; If you don't the next case will also be executed and so on.
Conditions, Arguments and Expressions are parts of 'speech' of the PHP Language. They are not interchangeable. Their difference mainly lies in where in a PHP sentence (aka a 'statement') they can be used, and are defined by the grammar of the PHP language.
Statements end in semicolons or are enclosed by curly braces ( { and } )
Expressions evaluate to a value, e.g. 1+2 is an expression, and so is $a = 1+2. $a = 1 + 2; is a statement made of a single expression. $a = $b = 1 + 2; is a statement made of two expressions.
Condition is another word for a boolean expression. A boolean expression is an expression that evaluates to either a value of true or a value of false.
Argument is the value passed in to a parameter of a function. People sometimes talk about the 'argument' to an if statement, but this is technically not correct. if/while/for/foreach take expressions. The fact that they look like a function call is just syntatic sugar.
I would use this terminology:
if (condition)
body
while (condition)
body
switch (subject) {
cases
}
That said, some people will refer to the condition of a while loop as an argument, for example. In my opinion this isn't the best terminology, because an argument is something passed to a function, and if/while/switch are not functions in PHP (they are in some languages).
But you're right, some people will say "the argument of the while loop." Just understand that they mean "the condition of the while loop."
While is repeating cycle. It means "do all in brackets while my expresion"
if and switch are the same. The diference is just in readibility.
An expression is simply something that expresses something - in a if/switch/while, the expression determines which code path should be taken. Usually the expression boils down to a simple boolean true/false value, or something that can be converted into a boolean value.
However, you can also consider the expression to be an argument, if you pretend that if() and while() are function calls - the expression are the arguments for those pseudo-functions. But again, the arguments will get distilled down to simple boolean values.
Related
So the syntax for if statements is:
if(condition){
//code to execute
}
Then why do functions when placed in place of conditions work in PHP.
In PHP (and many languages) there is no specific concept of a "condition"; the actual definition of an if statement is:
if(expression){
//code to execute
}
An "expression" is simply anything that can be evaluated and results in a value. A single value, like 42 is an expression on its own, as is a simple sum like 1 + 1. A function call like strlen('hello') is also an expression, evaluating to the result of the function; the function has to be run, which may have side effects, to determine that result. Expressions can be arbitrarily complex by linking then with operators, like strlen('hello') * 2 + 1.
Commonly in an if statement, you'd have something like $foo === $bar - this is just an expression that uses the === operator to give a boolean result, either true or false. PHP will evaluate that expression, and then decide whether to run the conditional code based on the result. The expression can be as simple or complex as you want - if(true) is valid, though not often useful, and so is if((strlen('hello') * 2 + 1) > 10).
If the result of the expression is not a boolean, PHP "coerces" it into one, as described on the manual page about the boolean type. For instance strlen($foo) evaluates to an integer, and all integers other than zero coerce to true, so if(strlen($foo)) acts like if(strlen($foo) !== 0).
As well as function calls, there are other expressions which have side effects. For instance, an assignment can also be used as an expression, evaluating to the value assigned. This lets you do things like $foo = $bar = 0; where $foo is assigned the result of running $bar = 0; which is of course 0. It also lets you put assignments inside if statements, like if ( $result = getData() ) { ... }, which is shorthand for $result = getData(); if ( $result ) { ... } This technique should be used with care, though, because at a glance it can be hard to spot the difference between = (assignment) and == (weak comparison).
The values returned in a PHP if condition are not restricted to be "strictly" Boolean, however the condition is expected to be Boolean. Why? Because all PHP variables types (inbuilt or user-defined) can be implicitly type-casted (converted automatically) to Boolean. According to the PHP manual:
To explicitly convert a value to bool, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a bool argument.
The PHP manual also explicitly specifies the falsy values for the different variable types including user defined types with all other values not specified being truthy:
the following values are considered false:
the boolean false itself
the integer 0 (zero)
the floats 0.0 and -0.0 (zero)
the empty string, and the string "0"
an array with zero elements
the special type NULL (including unset variables)
SimpleXML objects created from attributeless empty elements, i.e. elements which have neither children nor attributes.
Every other value is considered true (including any resource and NAN).
Therefore, to explicitly answer your question:
why do functions when placed in place of conditions work in PHP?
One reason I know of, is so you can conveniently perform assignments in the conditions:
function inverse_power($base, $exp)
{
if($power = pow($base, $exp)) {
return 1/$power;
}
else {
return "logical error: you can't divide by zero";
}
}
echo inverse_power(2,1); // 0.5
echo inverse_power(0,1); // logical error: you can't divide by zero
From the above example, you see the feature saves me multiple lines of code. Note that $power is not explicitly Boolean, but will be automatically converted to Boolean only to test the condition. The actual value of $power still persists throughout the function.
Because a condition is a boolean and functions can return booleans. And for conditions to work, the condition itself has to be evaluated, so it can be a function that is executed also.
Unfortunately I haven't found any official resource on this.
Is it allowed to use the ternary operator like this, to shorten and if/else statement:
(isset($someVar) ? $this->setMyVar('something') : $this->setMyVar('something else'));
In the PHP documentation, the ternary operator is explained with this example:
$action = (empty($_POST['action'])) ? 'standard' : $_POST['action'];
This makes me believe that my use case might work, but it not really valid because a setter function does not return anything.
Yes, you can. From the PHP Doc:
[...] the ternary operator is an expression, and [...] it doesn't evaluate to a variable, but to the result of an expression.
That quoted, although the ternary is mostly used for assigning values, you can use it as you suggested because a function call is an expression so the appropriate function will be evaluated (and therefore executed).
If your setter function would return a value, it would simply not be assigned to anything and would therefore be lost. However, since you said your setter doesn't return anything, the whole ternary operator will evaluate to nothing and return nothing. That's fine.
If this is more readable than a regular if/else is a different story. When working in a team, I would suggest to rather stick to a regular if/else.
Or, how about going with this syntax, which would be more common?
$this->myVar = isset($someVar) ? 'something' : 'something else';
Or, using your setter:
$this->setMyVar(isset($someVar) ? 'something' : 'something else');
I have a function,
abc(string $x, bool $y)
How can I use the ternary operator inside the function call expression? I tried this but gave
unexpected T_RETURN error
Code:
abc('Hello', return (1==1)?true:false);
In imperative languages like PHP, return is only used to return from a function. We call things like return statements, because they are things that one states in a function body.
On the other hand, things that have values or evaluate to values, like the number 2, or the expression 2 + 5 are called expressions.
You can think of return as a way to convert an expression (i.e., "hello, world!") into an action (i.e., return "hello,world!")
You can think of expressions like noun clauses (i.e., "a rock") and statements like actions (i.e., "give the rock to your boss").
In this case, PHP, like most imperative languages, expects you to only use expressions as arguments to functions.
Think about it -- what would it mean to pass an action as an argument to a function, or to add two actions together?
In the code you have, you want to call abc with the first argument set to 'Hello' and the second set to the value of the expression (1 == 1)?true:false. In this case, you don't need the return statement because (1==1)?true:false is already an expression, so you can just do:
abc('Hello', (1==1)?true:false);
You don't need the return there. Try replacing the line above with
abc('Hello', (1==1)?true:false);
try this
abc('Hello', $y = (1==1)?true:false);
function abc($x, $y)
{
echo $x." ".$y;
}
OUTPUT :
Hello 1
Since $y is already supposed to be a boolean you can't need a ternary operator in your call. A ternary operator uses a boolean value to choose between two other values; if those other values are only true and false then the statement is redundant. You can simply write:
abc('Hello', 1==1);
Can any one explain me following construct.
I do googling for this about 2 hours but can't understand.
public function __construct($load_complex = true)
{
$load_complex and $this->complex = $this->getComplex();
}
See: http://www.php.net/manual/en/language.operators.logical.php
PHP uses intelligent expression evaluation. If any of AND's operands evaluates to false, then there is no reason to evaluate other, because result will be false.
So if $load_complex is false there is no need to evaluate $this->complex = $this->getComplex();
This is some kind of workaround, but I do not suggest to use it, because it makes your code hard to read.
Specifically to your example $this->complex = $this->getComplex() if and only if $load_complex is set to true.
LIVE DEMO
NOTE: If any one of OPERAND result becomes 'false' in short
circuit AND evaluation means, the part of statement will be
OMITTED because there is no need to evaluate it.
Dont code like below line because, you may get probably logical
error while you are putting Expression instead of assigning values
to the variable on LEFT HAND SIDE...
$load_complex and $this->complex = $this->getComplex();
I have modified below with conditinal statement for your needs...
if($load_complex and $this->complex) {
$this->getComplex();
}
I have a PHP script that runs through an array of values through my own custom function that uses the PHP function preg_match. It's looking for a match with my regular expression being $valueA, and my string to search being $valueB, and if it finds a match, it returns it to $match, otherwise I don't want my IF statement to run.
Now, I'm having no problem with this IF statement running if the function finds a match (in other words, is TRUE);
if ($match = match_this($valueA, $valueB))
{
//do this
}
HOWEVER, if I wanted to compare an additional condition to check if it is also TRUE, and only run the IF statement when both are TRUE, I run into problems;
if ($match = match_this($valueA, $valueB) && $x == 'x')
{
//do this
}
Instead of the statement running as normal when both conditions are TRUE, I end up outputting a 1 from $match instead of what my $match value should be.
I can sort of see what's happening. My IF statement is just returning a literal boolean TRUE into $match, instead of my value returned from match_this();
Is this because I can only return one sense of TRUE?
I can get around the problem by having two nested IF statements, but for the sake of clean code I'd like to be able to compare multiple conditions in my IFs which includes functions that return values.
Are there different kinds of TRUE? If so, how do I compare them in this way? Or is there an easier method? I suppose I could just put a second IF statement inside my function and pass my second condition through the function, but then my function wouldn't be very clearly defined in terms of its purpose.
I've ran into this problem before and didn't quite know what I was looking for. Hope someone can help.
if (($match = match_this($valueA, $valueB)) && $x == 'x')
^ ^
You missed an extra set of brackets.
Without the extra set of brackets around $match = match_this($valueA, $valueB), the evaluation of the && is performed first and finally result is assigned to $match.
Alternatively, you could use and (which has lower precedence than assignment =) instead of &&
PHP Operator Precedence
if ($match = match_this($valueA, $valueB))
^---wrong operator
You should be using == for equality tests. Right now you're just assigning the return values of match_this. Ditto for your other if()
as per the comments below, if you actually ARE wanting to do assignments within the if() structure, then you should slap a very-large-blinking-neon-bright comment/warning above the code to say that this is intended behavior. In most any language and most any other person looking at this code later on will assume it's a typo and change the assignment to an equality test.