initialise variable using or operator - php

I want to initialise a variable with the contents of another variable, or a predefined value, if said other variable is not set.
I know I could use
if(isset($var1)){
$var2 = $var1;
} else{
$var2 = "predefined value";
}
I thought doing it like this would be more elegant:
$var2 = $var1 || "predefined value";
Last time I checked, this did work (or my memory is fooling me). But here, when I print $var2, it is always 1. It seems PHP checks if the statement $var1 || "predefined value" is true and assigns 1 to $var2.
I want "predefined value" to be assigned to $var2, in case $var1 doesn't exist.
Any peculiarity of PHP I'm missing here to make this work?
Thanks in advance

I generally create a helper function like this:
function issetor(&$var, $def = false) {
return isset($var) ? $var : $def;
}
and call it with the reference of the variable :
$var2 = issetor($var1, "predefined");

I just read that in PHP 7, there will be a new abbreviation for
$c = ($a === NULL) ? $b : $a;
It will look like this:
$c = $a ?? $b;
And can be extended like this:
$c = $a ?? $b ?? $c ?? $d;
explanation: $c will be assigned the first value from the left, which is not NULL.

Related

Not sure how to write this IF statement?

I'm not sure how to write this. I have a variable called $group the value could be a,b or c. I also have variables called $a, $b and $c. How do I write something that states if $group=a then use $a, if $group=b then use $b and if $group=c then use $c. Hope that makes sense.
Do you want this ??
$a = "a"; // $a is variable and "a" is its value and its a string.
$b = "b";
$c = "c";
if ($group == "a") // here a is just string value not variable.
{
echo $a;
}
elseif ($group == "b")
{
echo $b;
}
else
{
echo $c;
}
Or
Variable of variables
Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:
<?php
$a = 'hello';
?>
A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.
<?php
$$a = 'world';
?>
At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:
<?php
echo "$a ${$a}";
?>
produces the exact same output as:
<?php
echo "$a $hello";
?>
i.e. they both produce: hello world.
For more info click here
With Rahul's help and a tiny bit of tweaking this was my working end result.
if ($group == "a")
{
$group=$a;
}
elseif ($group == "b")
{
$group=$b;
}
else
{
$group=$c;
}

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)
);

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';

In PHP, what's the diff : $var2=$var1 ; $var2=&$var1; [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Reference assignment operator in php =&
$var2 = $var1;
$var2 = &$var1;
Example:
$GLOBALS['a']=1;
function test()
{
global $a;
$local=2;
$a=&$local;
}
test();
echo $a;
Why is $a still 1 ?
The operator =& works with references and not values.
The difference between $var2=$var1 and $var2=&$var1 is visible in this case :
$var1 = 1;
$var2 = $var1;
$var1 = 2;
echo $var1 . " " . $var2; // Prints '2 1'
$var1 = 1;
$var2 =& $var1;
$var1 = 2;
echo $var1 . " " . $var2; // Prints '2 2'
When you use the =& operator you don't say to $var2 "take the value of $var1 now" instead you say something like "Your value will be stored at the exact same place that the value of $var1".
So anytime you change the content of $var1 or $var2, you will see the modification in the two variables.
For more informations look on PHP.net
EDIT :
For the global part, you'll need to use $GLOBALS["a"] =& $local; Cf. documentation.
When you do $var2 = $var1, PHP creates a copy of $var1, and places it in $var2. However, if you do $var2 = &$var1, no copy is made. Instead, PHP makes $var2 point at $var1 - what this means is that you end up with two variables that point at the exact same thing.
An example:
$var1 = "Foo";
$var2 = $var1; // NORMAL assignment - $var1's value is copied into $var2
$var3 = &$var1; // NOT normal copy!
echo $var2; // Prints "Foo".
echo $var3; // Also prints "Foo".
$var1 = "Bar"; // Change $var1.
echo $var2; // Prints "Foo" as before.
echo $var3; // Now prints "Bar"!
global $a;
This is equivalent to:
$a = &$GLOBALS['a'];
When you assign $a a new reference, you're changing $a and not $GLOBALS['a'].
What do you expect to be output below?
$GLOBALS['a']=1;
function test()
{
$a='foobar'; // $a is a normal variable
$a=&$GLOBALS['a']; // same as: global $a;
$local=2;
$a=&$local;
}
test();
echo $a;

Is there a way to bind variables? PHP 5

Using PHP 5 I would like to know if it is possible for a variable to dynamically reference the value
of multiple variables?
For example
<?php
$var = "hello";
$var2 = " earth";
$var3 = $var.$var2 ;
echo $var3; // hello earth
Now if I change either $var or $var2 I would like $var3 to be updated too.
$var2 =" world";
echo $var3;
This still prints hello earth, but I would like to print "hello world" now :(
Is there any way to achieve this?
No, there is no way to do this in PHP with simple variables. If you wanted to do something like this in PHP, what you'd probably do would be to create a class with member variables for var1 and var2, and then have a method that would give you a calculated value for var3.
This should do the trick. I tested it on PHP 5.3 and it worked. Should also work on any 5.2.x version.
You could easily extend this with an "add"-Method to allow an arbitrary number of strings to be placed in the object.
<?php
class MagicString {
private $references = array();
public function __construct(&$var1, &$var2)
{
$this->references[] = &$var1;
$this->references[] = &$var2;
}
public function __toString()
{
$str = '';
foreach ($this->references as $ref) {
$str .= $ref;
}
return $str;
}
}
$var1 = 'Hello ';
$var2 = 'Earth';
$magic = new MagicString($var1, $var2);
echo "$magic\n"; //puts out 'Hello Earth'
$var2 = 'World';
echo "$magic\n"; //puts out 'Hello World'
No. Cannot be done without utilizing some sort of custom String class.
Check the PHP manual for types and variables, especially this passage:
By default, variables are always
assigned by value. That is to say,
when you assign an expression to a
variable, the entire value of the
original expression is copied into the
destination variable. This means, for
instance, that after assigning one
variable's value to another, changing
one of those variables will have no
effect on the other. For more
information on this kind of
assignment, see the chapter on
Expressions.
it's a bit late, but it's interesting question.
You could do it this way:
$var = "hello";
$var2 = " earth";
$var3 = &$var;
$var4 = &$var2;
echo $var3.$var4; // hello earth
From my point of view the following code is a little closer to the required:
$a = 'a';
$b = 'b';
$c = function() use (&$a, &$b) { return $a.$b; };
echo $c(); // ab
$b = 'c';
echo $c(); // ac
Create a function.
function foobar($1, $2){
$3 = "$1 $2";
return $3;
}
echo foobar("hello", "earth");
echo foobar("goodbye", "jupiter");

Categories