PHP variable declaration shorthand (similar to JavaScript) - php

In JavaScript, I can do this:
var somevar = {
propertyTwo : false,
propertyThree : "hello!"
}
var test = somevar.propertyOne || somevar.propertyTwo || somevar.propertyThree
alert(test); //displays "hello!"
Is there a similar functionality in PHP for this?
Haven't been able to find anything online.
I tried this, but PHP just treats it like a comparison and echo's 1 (true)
$somevar = array(
'propertyTwo' => false,
'propertyThree' => "hello!"
);
$test = $somevar['propertyOne'] || $somevar['propertyTwo'] || $somevar['propertyThree'];
echo $test; //displays '1'
Not really a big deal if there isn't, but I figured that with all of the bells and whistles provided in php 5.x, there would be some kind of shorthand for assigning the first true value in a list of values to a single variable like that.
I suppose I could write a function.
EDIT :
As I suspected, PHP doesn't have the same quirk.
Quick function I wrote
function assign_list($list){
foreach($list as $v)
if(isset($v) && $v) return $v;
return false;
}
Just pass it an array of stuff

The following will work in PHP >= 5.3, but you will still receive a Notice Error because propertyOne is not defined.
<?php
$somevar = array(
'propertyTwo' => false,
'propertyThree' => "hello!"
);
$test = $somevar['propertyOne'] ?: $somevar['propertyTwo'] ?: $somevar['propertyThree'];
echo $test; //displays 'hello!'
You could however work around this by supressing the variables, but it is highly unrecommended:
$test = #$somevar['propertyOne'] ?: #$somevar['propertyTwo'] ?: #$somevar['propertyThree'];

This doesn't work in PHP, and here's why:
$somevar['propertyOne'] = false;
$somevar['propertyTwo'] = true;
$test = $somevar['propertyOne'] || $somevar['propertyTwo'];
Imagine typing that query into an if statement:
if( $somevar['propertyOne'] || $somevar['propertyTwo'] ){ ... }
This will return true (evaluates to 1) if either variable is true.
Now, if we make all of the variables = false:
$somevar['propertyOne'] = false;
$somevar['propertyTwo'] = false;
$test = $somevar['propertyOne'] || $somevar['propertyTwo'];
The variable returns false (evaluates to 0).
Another thing we can do is:
$somevar['propertyOne'] = true;
$somevar['propertyTwo'] = true;
$test = $somevar['propertyOne'] && $somevar['propertyTwo'];
This will return true (evaluates to 1) as both variables meet the criteria.
This means that we can do things like this in PHP though:
$test = $somevar['propertyOne'] || $somevar['propertyTwo'];
if($test){ ... }
TL,DR: In PHP you are storing the result of the expression into a variable, not doing any validation on anything.

Related

Boolean has wrong value after operation [duplicate]

I remember reading a while back in regards to logical operators that in the case of OR, using || was better than or (or vice versa).
I just had to use this in my project when it came back to me, but I can't remember which operator was recommended or if it was even true.
Which is better and why?
There is no "better" but the more common one is ||. They have different precedence and || would work like one would expect normally.
See also: Logical operators (the following example is taken from there):
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
They are used for different purposes and in fact have different operator precedences. The && and || operators are intended for Boolean conditions, whereas and and or are intended for control flow.
For example, the following is a Boolean condition:
if ($foo == $bar && $baz != $quxx) {
This differs from control flow:
doSomething() or die();
The difference between respectively || and OR and && and AND is operator precedence :
$bool = FALSE || TRUE;
interpreted as ($bool = (FALSE || TRUE))
value of $bool is TRUE
$bool = FALSE OR TRUE;
interpreted as (($bool = FALSE) OR TRUE)
value of $bool is FALSE
$bool = TRUE && FALSE;
interpreted as ($bool = (TRUE && FALSE))
value of $bool is FALSE
$bool = TRUE AND FALSE;
interpreted as (($bool = TRUE) AND FALSE)
value of $bool is TRUE
Source: http://wallstreetdeveloper.com/php-logical-operators/
Here is sample code for working with logical operators:
<html>
<head>
<title>Logical</title>
</head>
<body>
<?php
$a = 10;
$b = 20;
if ($a>$b)
{
echo " A is Greater";
}
elseif ($a<$b)
{
echo " A is lesser";
}
else
{
echo "A and B are equal";
}
?>
<?php
$c = 30;
$d = 40;
//if (($a<$c) AND ($b<$d))
if (($a<$c) && ($b<$d))
{
echo "A and B are larger";
}
if (isset($d))
$d = 100;
echo $d;
unset($d);
?>
<?php
$var1 = 2;
switch($var1)
{
case 1: echo "var1 is 1";
break;
case 2: echo "var1 is 2";
break;
case 3: echo "var1 is 3";
break;
default: echo "var1 is unknown";
}
?>
</body>
</html>
I know it's an old topic but still. I've just met the problem in the code I am debugging at work and maybe somebody may have similar issue...
Let's say the code looks like this:
$positions = $this->positions() || [];
You would expect (as you are used to from e.g. javascript) that when $this->positions() returns false or null, $positions is empty array. But it isn't. The value is TRUE or FALSE depends on what $this->positions() returns.
If you need to get value of $this->positions() or empty array, you have to use:
$positions = $this->positions() or [];
EDIT:
The above example doesn't work as intended but the truth is that || and or is not the same... Try this:
<?php
function returnEmpty()
{
//return "string";
//return [1];
return null;
}
$first = returnEmpty() || [];
$second = returnEmpty() or [];
$third = returnEmpty() ?: [];
var_dump($first);
var_dump($second);
var_dump($third);
echo "\n";
This is the result:
bool(false)
NULL
array(0) {
}
So, actually the third option ?: is the correct solution when you want to set returned value or empty array.
$positions = $this->positions() ?: [];
Tested with PHP 7.2.1
I don't think one is inherently better than another one, but I would suggest sticking with || because it is the default in most languages.
EDIT: As others have pointed out there is indeed a difference between the two.
There is nothing bad or better, It just depends on the precedence of operators. Since || has higher precedence than or, so || is mostly used.
Some languages use short-circuit, and others use full Boolean evaluation (if you know, this is similar to the directive $B in Pascal).
Explanations:
function A(){
...Do something..
return true;
}
function B(){
...Do something..
return true;
}
if ( A() OR B() ) { .....
In this example the function B() will never be executed. Since the function A() returns TRUE, the result of the OR statement is known from the first part without it being necessary to evaluate the second part of the expression.
However with ( A() || B() ), the second part is always evaluated regardless of the value of the first.
For optimized programming, you should always use OR which is faster (except for the case when the first part returns false and second part actually needs to be evaluated).

PHP Define var = one or other (aka: $var=($a||$b);)

Is there a way to define a php variable to be one or the other just like you would do var x = (y||z) in javascript?
Get the size of the screen, current web page and browser window.
var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
i'm sending a post variable and i want to store it for a later use in a session. What i want to accomplish is to set $x to the value of $_POST['x'], if any exist, then check and use $_SESSION['x'] if it exist and leave $x undefined if neither of them are set;
$x = ($_POST['x'] || $_SESSION['x');
According to http://php.net/manual/en/language.operators.logical.php
$a = 0 || 'avacado'; print "A: $a\n";
will print:
A: 1
in PHP -- as opposed to printing "A: avacado" as it would in a
language like Perl or JavaScript.
This means you can't use the '||' operator to set a default value:
$a = $fruit || 'apple';
instead, you have to use the '?:' operator:
$a = ($fruit ? $fruit : 'apple');
so i had to go with an extra if encapsulating the ?: operation like so:
if($_POST['x'] || $_SESSION['x']){
$x = ($_POST['x']?$_POST['x']:$_SESSION['x']);
}
or the equivalent also working:
if($_POST['x']){
$x=$_POST['x'];
}elseif($_SESSION['x']){
$x=$_SESSION['x'];
}
I didn't test theses but i presume they would work as well:
$x = ($_POST['x']?$_POST['x']:
($_SESSION['x']?$_SESSION['x']:null)
);
for more variables i would go for a function (not tested):
function mvar(){
foreach(func_get_args() as $v){
if(isset($v)){
return $v;
}
} return false;
}
$x=mvar($_POST['x'],$_SESSION['x']);
Any simple way to achieve the same in php?
EDIT for clarification: in the case we want to use many variables $x=($a||$b||$c||$d);
A simpler approach is to create a function that can accept variables.
public function getFirstValid(&...$params){
foreach($params as $param){
if (isset($param)){
return $param;
}
}
return null;
}
and then to initialize a variable i would do...
var $x = getFirstValid($_POST["x"],$_SESSION["y"],$_POST["z");
the result will be that the var x will be assign the first variable that is set or is set to null if none of the variables pass are set.
explanation:
function getFirstValid accepts a variable number of variable pointers(&...) and loops through each checking if it is set, the first variable encountered that is set will be returned.
Yes you need to use simple ternary operator which you have used within your example along with some other functions of PHP like as of isset or empty functions of PHP. So your variable $x will be assigned values respectively
Example
$x = (!empty($_POST['x'])) ? $_POST['x'] : (!empty($_SESSION['x'])) ? $_SESSION['x'] : NULL;
So the above function depicts that if your $_POST['x'] is set than the value of
$x = $_POST['x'];
else it'll check for the next value of $_SESSION if its set then the value of $x will be
$x = $_SESSION['x'];
else the final value'll be
$x = null;// you can set your predefined value instead of null
$x = (!empty($a)) ? $a : (!empty($b)) ? $b : (!empty($c)) ? $c : (!empty($d)) ? $d : null;
If you need a function then you can simply achieve it as
$a = '';
$b = 'hello';
$c = '';
$d = 'post';
function getX(){
$args = func_get_args();
$counter = 1;
return current(array_filter($args,function($c) use (&$counter){ if(!empty($c) && $counter++ == 1){return $c;} }));
}
$x = getX($a, $b, $c, $d);
echo $x;
Update
I've managed to create a function for you that achieves exactly what you desire, allowing infinite arguements being supplied and fetching as you desire:
function _vars() {
$args = func_get_args();
// loop through until we find one that isn't empty
foreach($args as &$item) {
// if empty
if(empty($item)) {
// remove the item from the array
unset($item);
} else {
// return the first found item that exists
return $item;
}
}
// return false if nothing found
return false;
}
To understand the function above, simply read the comments above.
Usage:
$a = _vars($_POST['x'], $_SESSION['x']);
And here is your:
Example
It is a very simply ternary operation. You simply need to check the post first and then check the session after:
$a = (isset($_POST['x']) && !empty($_POST['x']) ?
$_POST['x']
:
(isset($_SESSION['x']) && !empty($_SESSION['x']) ? $_SESSION['x'] : null)
);
PHP 7 solution:
The ?? operator.
$x = expr1 ?? expr2
The value of $x is expr1 if expr1 exists, and is not NULL.
If expr1 does not exist, or is NULL, the value of $x is expr2.
https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
It would be simple -
$x = (!empty($_POST['x']) ? $_POST['x'] :
(!empty($_SESSION['x']) ? $_SESSION['x'] : null)
);

assignment in PHP

I am learning php and read this example in this http://www.php.net/manual/en/language.types.boolean.php tutorial,
I want to understand what occur when assigning the return value of method to a variable, why it may change?? please see my questions in the code.
<?php
public function myMethod()
{
return 'test';
}
public function myOtherMethod()
{
return null;
}
if($val = $this->myMethod())
{
// $val might be 1 instead of the expected 'test'
** why it may returns 1??**
}
if( ($val = $this->myMethod()) )
{
// now $val should be 'test'
}
// or to check for false
if( !($val = $this->myMethod()) ) **what happens here????**
{
// this will not run since $val = 'test' and equates to true
}
// this is an easy way to assign default value only if a value is not returned:
if( !($val = $this->myOtherMethod()) ) **what happens here????**
{
$val = 'default'
}
?>
In this case:
if($val = $this->myMethod())
{
// $val might be 1 instead of the expected 'test'
}
I don't think that's true. $val should be 'test' here. Maybe in older versions of PHP there could have been a bug.
if(!($val = $this->myMethod()))
{
// this will not run since $val = 'test' and equates to true
}
Here myMethhod() is executed and returns 'test' which is assigned to $val. Then the result of that assignment is boolean negated. Since the string 'test' evaluates to true, !('test') evalutes to false and the if statement doesn't run.
if(!($val = $this->myOtherMethod()))
{
$val = 'default';
}
This is the opposite case. $val becomes null. And null evaluates to boolean false, so !(null) evaluates to true and the code in the block executes. So after this code runs $val contains 'default'; This poster is showing this as a way of assigning a default value to $val in the case that $this->myOtherMethod() fails to return anything useful.
why it may returns 1? It is not returning 1 but the actual value that is 'test' but since this value is assigned properly because this is not NULL, false or empty. the if statement evaluates to true.
// or to check for false
if( !($val = $this->myMethod()) ) **what happens here????**
{
// this will not run since $val = 'test' and equates to true
}
What is happening here? The if statement here will test if non NULL value has been assigned to $val i.e. $val is not null similar to if(!$val). Since its value is not NULL nor false The code inside if will not execute.
if( !($val = $this->myOtherMethod()) ) **what happens here????**
{
$val = 'default'
}
What is happening here? since the assignment to the $val inside if statement failed because function returned NULL, and since $val is NULL if statement evaluates true and code inside executes. It wouldn't execute if the function had returned other than NULL or false.
Sorry guys, but i think the previous answers are wrong. I'm not sure if this is a typo or a trick question, but with
if($val = $this->myMethod())
you're actually SETTING $val to whatever $this->myMethod() returns, so your if() statement always equals true here. if you want to compare it you would have to use
if($val == $this->myMethod())
Notice the '==' in here!
Try This:
public function myMethod()
{
return 'test';
}
public function myOtherMethod()
{
return null;
}
if($val = myMethod())
{
Do Something
}elseif ($val != myMethod()){
Do Something Else
}elseif ($val == myOtherMethod())
{
$val = 'default';
}
?>

How to change the variable being assigned via condition?

I want to change the variable being assigned based on condition, and I can seem to get it working.
$condition = false;
($condition !== false ? $array[1][$condition] : $array[1]) = 'Test';
In this example, if $condition isn't false, I want to assign the string "Test" to $array[1][$condition]. Otherwise, assign it to $array[1]
I can easily do this like this:
if ($condition !== false) {
$array[1][$condition] = 'Test'; }
else {
$array[1] = 'Test'; }
But due to the nature of the code this can get quite cluttered, which is why I wish for it to be an inline conditional statement.
Thanks for any help!
$condition = false;
$array[1][$condition] = ($condition !== false ? 'Test' : $array[1]);
$condition !== false ? $array[1][$condition] = "Test" : $array[1] = "Test";
The result of the ternary operator is not a reference, so you can't use it as the left-hand side of an assignment.
You might be able to use variable variables and references, but this might just add complexity without providing any real benefit.
Something like this:
$a =& $array[1];
$b =& $array[1][$condition];
$var = ($condition !== false ? 'b' : 'a');
$$var = 'Test';

Logical Operators, || or OR?

I remember reading a while back in regards to logical operators that in the case of OR, using || was better than or (or vice versa).
I just had to use this in my project when it came back to me, but I can't remember which operator was recommended or if it was even true.
Which is better and why?
There is no "better" but the more common one is ||. They have different precedence and || would work like one would expect normally.
See also: Logical operators (the following example is taken from there):
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
They are used for different purposes and in fact have different operator precedences. The && and || operators are intended for Boolean conditions, whereas and and or are intended for control flow.
For example, the following is a Boolean condition:
if ($foo == $bar && $baz != $quxx) {
This differs from control flow:
doSomething() or die();
The difference between respectively || and OR and && and AND is operator precedence :
$bool = FALSE || TRUE;
interpreted as ($bool = (FALSE || TRUE))
value of $bool is TRUE
$bool = FALSE OR TRUE;
interpreted as (($bool = FALSE) OR TRUE)
value of $bool is FALSE
$bool = TRUE && FALSE;
interpreted as ($bool = (TRUE && FALSE))
value of $bool is FALSE
$bool = TRUE AND FALSE;
interpreted as (($bool = TRUE) AND FALSE)
value of $bool is TRUE
Source: http://wallstreetdeveloper.com/php-logical-operators/
Here is sample code for working with logical operators:
<html>
<head>
<title>Logical</title>
</head>
<body>
<?php
$a = 10;
$b = 20;
if ($a>$b)
{
echo " A is Greater";
}
elseif ($a<$b)
{
echo " A is lesser";
}
else
{
echo "A and B are equal";
}
?>
<?php
$c = 30;
$d = 40;
//if (($a<$c) AND ($b<$d))
if (($a<$c) && ($b<$d))
{
echo "A and B are larger";
}
if (isset($d))
$d = 100;
echo $d;
unset($d);
?>
<?php
$var1 = 2;
switch($var1)
{
case 1: echo "var1 is 1";
break;
case 2: echo "var1 is 2";
break;
case 3: echo "var1 is 3";
break;
default: echo "var1 is unknown";
}
?>
</body>
</html>
I know it's an old topic but still. I've just met the problem in the code I am debugging at work and maybe somebody may have similar issue...
Let's say the code looks like this:
$positions = $this->positions() || [];
You would expect (as you are used to from e.g. javascript) that when $this->positions() returns false or null, $positions is empty array. But it isn't. The value is TRUE or FALSE depends on what $this->positions() returns.
If you need to get value of $this->positions() or empty array, you have to use:
$positions = $this->positions() or [];
EDIT:
The above example doesn't work as intended but the truth is that || and or is not the same... Try this:
<?php
function returnEmpty()
{
//return "string";
//return [1];
return null;
}
$first = returnEmpty() || [];
$second = returnEmpty() or [];
$third = returnEmpty() ?: [];
var_dump($first);
var_dump($second);
var_dump($third);
echo "\n";
This is the result:
bool(false)
NULL
array(0) {
}
So, actually the third option ?: is the correct solution when you want to set returned value or empty array.
$positions = $this->positions() ?: [];
Tested with PHP 7.2.1
I don't think one is inherently better than another one, but I would suggest sticking with || because it is the default in most languages.
EDIT: As others have pointed out there is indeed a difference between the two.
There is nothing bad or better, It just depends on the precedence of operators. Since || has higher precedence than or, so || is mostly used.
Some languages use short-circuit, and others use full Boolean evaluation (if you know, this is similar to the directive $B in Pascal).
Explanations:
function A(){
...Do something..
return true;
}
function B(){
...Do something..
return true;
}
if ( A() OR B() ) { .....
In this example the function B() will never be executed. Since the function A() returns TRUE, the result of the OR statement is known from the first part without it being necessary to evaluate the second part of the expression.
However with ( A() || B() ), the second part is always evaluated regardless of the value of the first.
For optimized programming, you should always use OR which is faster (except for the case when the first part returns false and second part actually needs to be evaluated).

Categories