how to call the array in $$variable - php

$var = "array";
$$var=array("1","2");
How can I call the array in $$var without using foreach? I want a method like $$var[0], but this doesn't work.

Use it like this:
echo ${$var}[0];

When you run this piece of code:
$var = "array";
$$var = array("1","2");
...it is identical to this:
$array = array("1","2");
So you can do this:
echo $array[0];
...or this:
echo ${$var}[0];
If you must use variable variables - and 99.99% of the time arrays are a better solution - you should always use braces for clarity and disambiguation.
See the variable variables reference for more information.

You need some curly braces:
${$var[1]}
OR
${$var}[1]
depending on which variable you are accessing.

Related

Message: Trying to get property of non-object error in php [duplicate]

Is there in PHP something similar to JavaScript's:
alert(test || 'Hello');
So, when test is undefined or null we'll see Hello, otherwise - we'll see the value of test.
I tried similar syntax in PHP but it doesn't seem to be working right... Also I've got no idea how to google this problem..
thanks
Edit
I should probably add that I wanted to use it inside an array:
$arr = array($one || 'one?', $two || 'two?'); //This is wrong
But indeed, I can use the inline '? :' if statement here as well, thanks.
$arr = array(is_null($one) ? "one?" : $one, is_null($two) ? "two ?" : $two); //OK
you can do echo $test ?: 'hello';
This will echo $test if it is true and 'hello' otherwise.
Note it will throw a notice or strict error if $test is not set but...
This shouldn't be a problem since most servers are set to ignore these errors. Most frameworks have code that triggers these errors.
Edit: This is a classic Ternary Operator, but with the middle part left out. Available since PHP 5.3.
echo $test ? $test : 'hello'; // this is the same
echo $test ?: 'hello'; // as this one
This only checks for the truthiness of the first variable and not if it is undefined, in which case it triggers the E_NOTICE error. For the latter, check the PHP7 answer below (soon hopefully above).
From PHP 7 onwards you can use something called a coalesce operator which does exactly what you want without the E_NOTICE that ?: triggers.
To use it you use ?? which will check if the value on the left is set and not null.
$arr = array($one ?? 'one?', $two ?? 'two?');
See #Yamiko's answer below for a PHP7 solution https://stackoverflow.com/a/29217577/140413
echo (!$test) ? 'hello' : $test;
Or you can be a little more robust and do this
echo isset($test) ? $test : 'hello';
As per the latest version use this for the shorthand
$var = $value ?? "secondvalue";
One-liner. Super readable, works for regular variables, arrays and objects.
// standard variable string
$result = #$var_str ?: "default";
// missing array element
$result = #$var_arr["missing"] ?: "default";
// missing object member
$result = #$var_obj->missing ?: "default";
See it in action: Php Sandbox Demo
I'm very surprised this isn't suggested in the other answers:
echo isset($test) ? $test : 'hello';
From the docs isset($var) will return false if $var doesn't exist or is set to null.
The null coalesce operator from PHP 7 onwards, described by #Yamiko, is a syntax shortcut for the above.
In this case:
echo $test ?? 'hello';
If you want to create an array this way, array_map provides a more concise way to do this (depending on the number of elements in the array):
function defined_map($value, $default) {
return (!isset($value) || is_null($value)) ? $default : $value;
// or return $value ? $default : $value;
}
$values = array($one, $two);
$defaults = array('one', 'two');
$values = array_map('defined_map', $values, $defaults);
Just make sure you know which elements evaluate to false so you can apply the right test.
Since php7.4, you can use the null coalescing assignment, so that you can do
$arr = array($one ??= "one?", $two ??= "two ?");
See the docs here
There may be a better way, but this is the first thing that came to my mind:
echo (!$test) ? "Hello" : $test;
Null is false in PHP, therefore you can use ternary:
alert($test ? $test : 'Hello');
Edit:
This also holds for an empty string, since ternary uses the '===' equality rather than '=='
And empty or null string is false whether using the '===' or '==' operator. I really should test my answers first.
Well, expanding that notation you supplied means you come up with:
if (test) {
alert(test);
} else {
alert('Hello');
}
So it's just a simple if...else construct. In PHP, you can shorten simple if...else constructs as something called a 'ternary expression':
alert($test ? $test : 'Hello');
Obviously there is no equivalent to the JS alert function in PHP, but the construct is the same.
alert((test == null || test == undefined)?'hello':test);
I recently had the very same problem.This is how i solved it:
<?php if (empty($row['test'])) {
echo "Not Provided";}
else {
echo $row['test'];}?></h5></span></span>
</div>
Your value in the database is in variable $test..so if $test row is empty then echo Not Provided

selecting array for array_push using Ternary Operator [duplicate]

This question already has an answer here:
Assigning variables by reference and ternary operator?
(1 answer)
Closed 1 year ago.
I have two arrays and I want to append to one or another based on a certain condition. The problem is that the array_push function should be called inside cases of a switch case inside a foreach loop, so using if-else means 20 extra lines of code. I thought I could do this using the Ternary Operator, but for some reason it doesn't work.
$arr1 = ['1', '2'];
$arr2 = ['a', 'b'];
$condition = False;
array_push($condition ? $arr1 : $arr2, 'new');
which produces this error:
array_push(): Argument #1 ($array) cannot be passed by reference
I thought $arr1 and $arr2 are references, and therefore you should be able to pass them, but something is not as it should be. At least that's how it behaves in C.
Have a look at the function signature for array_push():
array_push(array &$array, mixed ...$values): int
Notice the & in the first argument. That indicates that a reference must be passed.
Only variables can be passed by reference. A ternary expression is, well, an expression.
If you want to do this, you will need to first establish the reference, then pass it. And there's no easy way to shortcut that.
if( $condition) $ref = &$arr1; else $ref = &$arr2;
array_push($ref, 'new');
$ref = null; // clear reference

Two variable variables in one variable

I have a for-loop ($x++) within another for-loop ($i++) , and I want both $x AND $i to be part of a variable variable:
${'name'.$x.'place'.$i.''} = ...;
Such that I get:
$name1place1
$name1place2
$name1place3
$name2place1
$name2place2
$name3place1 etc. etc.
However, setting variables in the way quoted above does NOT work for me (i.e. with single quotations and two variable variables). I get the error "Notice: Undefined variable [...]".
The following works:
${"name$x"} = ...;
(using double quotations and just one variable variable.)
How can I set variable variables with both $x and $i within the variable name? Thank you!
You can do this by using curly braces within your variable name assignment to separate $x from the place:
$x = 4;
$i = 5;
${"name{$x}place{$i}"} = "test";
echo $name4place5;
Output:
test
However it would really make a lot more sense to just use an array:
$name[$x][$i] = "test2";
echo $name[$x][$i];
Demo on 3v4l.org

Assigning values to arrays in php

I'm a bit curious about why does this work:
$arr1[] = $arr2[] = $value;
If I'm correct, first the value is pushed to the end of arr2. Then $arr2[] pushed to the end of $arr1. This is where I'm confused. If I do it separately like:
$var = $arr2[];
I get "Fatal error: Cannot use [] for reading..."
But how come [] works for reading when I'm doing multiple assignments in the same statement?
Because $var is not an array. To make $var an array:
$var = array();
or,
$var = $arr2;
If I'm correct, first the value is pushed to the end of $arr2. Then
$arr2[] pushed to the end of $arr1.
That's not correct. What happens is that $value is pushed to the end of both arrays, one at a time. The phrase "$arr2[] is pushed" is meaningless because the expression $arr2[] is not valid in a read context (i.e. it does not "have a value"), which is exactly what the error message you got in your second attempt says.
But how come [] works for reading when I'm doing multiple assignments
in the same statement?
Chaining the assignment operator in PHP does not work quite as it does in certain other languages. In particular,
$x = $y = (expr);
is treated in the same way as if you had written
// the purpose of $temp is to prevent (expr) from being evaluated twice,
// because evaluating it might have side effects (e.g. think $i++)
$temp = (expr);
$x = $temp;
$y = $temp;
That is, $arr1[] is not being assigned the value $arr2[] but rather $value directly because the assignment operator evaluates to its right-hand-side operand.
This suggestion is wrong:
Then $arr2[] pushed to the end of $arr1.
From the manual:
The value of an assignment expression is the value assigned. That is,
the value of "$a = 3" is 3. This allows you to do some tricky things...
So, first assignment operator $arr2[] = $value returns value of $value, which can be assigned further.
But how come [] works for reading when I'm doing multiple assignments in the same statement?
it doesnt.
try var dumping it
$a = array();
var_dump ($a[] = 2);
which returns
int(2)
That value is then passed to the second so $b = $a = 2
does $a=2, which returns 2, then assigns that value to $b[]
var_dump($a[]);
on the other hand doesnt make sense as var_dump($a[]) doesnt exist, it can only be used for writing to an array
$arr1[] = $arr2[] = $value; this works because you are first assigning a variable or string to an array $arr2[] and then again assiging that array to another array $arr1[].
But in case $var = $arr2[]; you are assing array to a normal variable which is not permitted.
For doing this you need to make $var as an array as $var = array();

Is there a shorthand way to assign a group of variables to each of the values of an array in php?

In perl I can write
($var1, $var2, $var3) = split(/:/, "foo:bar:blarg")
to split a string by colon and assign each array element to $var1, $var2 and $var3. Is there a similar syntax for this in php? I have to use the variables in a lot of my code so I want them to have meaningful names, and writing variable assignment code like
$array = split(/:/, "foo:bar:blarg");
$var1 = $array[0];
$var2 = $array[1];
//etc
is tedious when i have to do this a lot.
PHP has the list language construct to do that.
list($var1, $var2, $var3) = split(":", "foo:bar:blarg");

Categories