How to access php variable using concatenation [duplicate] - php

This question already has answers here:
PHP - Variable inside variable?
(6 answers)
Closed 8 years ago.
I want to access a variable that is either called $item1, $item2 or $item3.
I want to access this variable inside a for loop where $i is ++ every time. using $item.$i or something similar. However using that code means that I am trying to join the contents of two variables, and there is no variable called $item.

Arrays: A Better Method
While PHP does permit you to build dynamic variable names from various other values, you probably shouldn't in this case. It seems to me that an array would be more appropriate for you:
$items = array( 0, 12, 34 );
You could then access each value individually:
echo $items[0]; // 0
echo $items[1]; // 12
Or loop over the entire set:
foreach ( $items as $number ) {
echo $number; // 1st: 0, 2nd: 12, 3rd: 34
}
Merging Multiple Arrays
You indicated in the comments on the OP that $item1 through $item3 are already arrays. You could merge them all together into one array if you like with array_merge(), demonstrated below:
$item1 = array( 1, 2 );
$item2 = array( 3, 4 );
$item3 = array( 5, 6 );
$newAr = array_merge( $item1, $item2, $item3 );
print_r( $newAr );
Which outputs:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
If You Must: Dynamic Variable Names
For completeness, if you were to solve your problem by dynamically constructing variable names, you could do the following:
$item1 = 12;
$item2 = 23;
$item3 = 42;
for ( $i = 1; $i <= 3; $i++ ) {
echo ${"item".$i} . PHP_EOL;
}

build the variable name you want to access into another variable then use the variable variable syntax
<?php
$item1 = 'a';
$item2 = 'b';
$item3 = 'c';
for ($i = 1; $i<=3; $i++) {
$varname = 'item' . $i;
echo $$varname;
}
?>
output:
abc
Note there are other ways to do this, see the manual.

Use ${'item'.$i}
If $i == 1, then you will access $item1.
But it's better to use arrays in your case.

for ($i =1;$i<4;$i++){
$var = 'item'.$i;
echo $$var;
}
Here you are using the the double $ to create a variable variable.

Can you use an array instead of individual variables? then you can reference array elements by index value based in i.
$items = array();
$i = 1;
$items[$i] = "foo";
$i++;
$items[$i] = "bah";
echo $items[1], $items[2]; // gives "foobah"

It's a little late, and the accepted answer is the proper way to do this, but PHP does allow you to access variable variable names in the way OP describes:
<?php
$item1 = 'a';
$item2 = 'b';
$item3 = 'c';
for($i=1;$i<=3;$i++)
echo ${"item$i"}; //Outputs: abc
?>

Related

Php use a string as variable name print_r

my scenario is as follow i have lets say 2 arrays $array_0 and $array_1 then i want to print it in a while better in a for
for ($i=0;$i<=1;$i++){
print_r(array($array?));
}
how i should declare de array to print_r i try set the string of the name in a variable before but maybe its lacks something
for ($i=0;$i<=1;$i++){
$str_array='$array_'.$i;
print_r(array($str_array));
}
but that prints something like
Array
(
[0] => $array_0
)
Array
(
[0] => $array_1
)
Sounds like you're looking for variable variables.
$array_0 = ['foo'];
$array_1 = ['bar'];
for ($i = 0; $i <= 1; $i++) {
print_r(${'array_' . $i}); // Here we "build" the variable name
}
Here's a demo: https://3v4l.org/PLApU
You can read more about variable variables in the manual: https://www.php.net/manual/en/language.variables.variable.php
You need to use "variable variable" by putting a second dollar sign. Here is an example:
$arr_1 = array(1=>'a', 2=>'b');
$arr_2 = array(1=>'c', 2=>'d', 3=>'e');
for($i=1; $i<=2; $i++){
$arrname = 'arr_'.$i;
print_r(${$arrname});
}
You can use $$arrname instead of ${$arrname}; however I found the latter more clear to understand what's happening.

I want to know the correct syntax of declaring multiple variables in php with small changes like mentioned below

$str='abcde';//for sub-question numbers
for ($i=1; $i <=10 ; $i++) {//i loop is for question numbers 1 to 10
for ($j=0; $j<5 ; $j++) {//j loop is for sub-questions from a to e
$q{$i}{$str[$j]}=$_POST['q{$i}{$str[j]}'];//not sure about this part
}
}
Here the main idea is to create 50 variables from q1a,q1b,... till q10d,q10e.
I'm not 100% clear on what the values of those variables will be, but here is how to create an array with those variable names in them.
$questions = array(1,2,3,4,5,6,7,8,9,10); //questions
$subQuestions = array('a','b','c','d','e'); //sub-question
$allQuestions = array();
foreach($questions as $question) {//loop the questions
foreach($subQuestions as $subQ) {//loop the sub questions
// I'm not clear what you're trying to do here -> $q{$i}{$str[$j]}=$_POST['q{$i}{$str[j]}'];//not sure about this part
$allQuestions["q" . $question . $subQ] = "I'm an empty value right now"; //what value goes here?
}
}
var_dump($allQuestions);
You can do something like this
$values = array("q1a", "q1b", "q1c", "q1d", "q1e", "q2a", "q2b", "q2c", "q2d", "q2e");
for($i=;$i<$sizeof($values);$i++)
{
$values[$i] = $_POST['q{$i}{$str[j]}'];
}
If all your POST vars which you want to grab are prepended with q then just filter them with array_filter().
Then you can use extract(), but tbh, you should just use the array.
<?php
$_POST = [
'q1' => 'baz',
'foo' => 'bar',
];
$q = array_filter($_POST, function($k) {
return substr($k, 0, 1) === 'q';
}, ARRAY_FILTER_USE_KEY);
extract($q);
// filtered array
print_r($q);
// extract'ed
echo $q1;
Result:
Array
(
[q1] => baz
)
baz
https://3v4l.org/rvMR6

How to call variables sharing the same name but ending with different numbers by assigning a variable to these numbers

I couldn't find a better title for this problem. I have variables like this: $var1, $var2, $var3.
In a for loop, I want to display these variables:
for ( $j = 1; $j <= 3; $j++ ) {
echo $var$j;
}
Of course this won't work, but what is the syntax to do it? If $var1 = 1, $var2 = 2 and $var3 = 3, I want this result: "123".
Use curly braced syntax (known as variable variables):
for ( $j = 1; $j <= 3; $j++ ) {
echo ${"var$j"};
}
Also, as #Alnitak mentioned in comment:
if you're using numbers to handle a set of variables like this, you should have used an array in the first place.
So array is definately an option, as it might be exact case for it's usage.
This is how to solve your problem:
How to put a value inside :
// $content is an array of values.
for ( $j = 1; $j <= 3; $j++ ) {
$var_name = "var".$j;
$$var_name = $content[$j];
}
And how to read them :
for ( $j = 1; $j <= 3; $j++ ) {
$var_name = "var".$j;
echo $$var_name;
}
But may I suggest to use arrays:
// $content is an array of values.
foreach ( $content as $key=>$value) {
echo $content[$key];
echo $value; //same as previous line
unset($content[$key]);//to remove a value from an array
}
If you can, switch to using arrays instead of these variables. If you can't, you can still use an array:
foreach (array($var1, $var2, $var3) as $current) {
echo $current;
}
I think one should use an Array instead of lots of unnecessary variables.
Keeping things structured, as what is held here is a Data Structure at all.
One may implode/join them using an empty value as is:
$values = [1,2,3];
echo join('', $values);
As simple as that! Think of it!
By the sake of portability, there may be the case where an Associative Array is used, let's say when the data is fetched from a Database Rowset.
As of PHP has a way to extract array values only, one can use:
$values = [
'value1' => 1,
'value2' => 2,
'value3' => 3
];
echo join('', array_values($values));
And, finally, considering the previous associative concept, it is also possible to use object properties:
$obj = new \stdClass();
$obj->value1 = 1;
$obj->value2 = 2;
$obj->value3 = 3;
echo join('', array_values(get_object_vars($obj)));
This will work for you:
$var1 = "1";
$var2= "2";
$var3 = "3";
for ( $j = 1; $j <= 3; $j++ ) {
echo ${"var".$j};
}
and the output will be
123
The syntax is
${"firstPart".$lastPart};
which is equal to
$firstPartlastPart
You may read about it more here: http://www.php.net/manual/en/language.variables.variable.php

How to store an array into a session variable in php

//Returns 10 question from questions table
$result = mysqli_query($con,"SELECT question FROM questions ORDER BY rand() LIMIT 10' ");
while($row = mysqli_fetch_row($result))
{
$que[]=$row[0];
}
Now I need to store this whole set of $que[] in a session variable. (i.e 10 questions)
Something like this
$_SESSION['question'] = $que[];
$my_array[] = $_SESSION['question'];
so that $my_array[0] returns first question, $my_array[1] returns second questions and like that.
(Thanx for the help in advance)
Assign
$_SESSION['question'] = $que;
print_r($_SESSION['question'][0]); will give you first question.
You are almost correct, you only need the [] when adding to the array.
$_SESSION['question'] = $que;
Make sure that you have a session going first, placing this at the top of your script will start a session if one doesn't already exist:
if( !isset( $_SESSION ) ) {
session_start();
}
To pull it back up:
$array = $_SESSION['question']; //Assigns session var to $array
print_r($array); //Prints array - Cannot use echo with arrays
Final Addition
To iterate over the array, you can typically use for, or foreach. For statements really only work well when your array keys are incremental (0, 1, 2, 3, etc) without any gaps.
for( $x = 0, $max = count($array); $x < $max; ++$x ) {
echo $array[$x];
}
foreach( $array as &$value ) {
echo $value;
}
Both have been written in mind for performance. Very important to know that when using a reference (&$value, notice the &) that if you edit the reference, the original value changes. When you do not use by reference, it creates a copy of the value. So for example:
//Sample Array
$array = array( '0' => 5, '1' => 10 );
//By Reference
foreach( $array as &$value ) {
$value += 2; //Add 2 to each value
echo $value; //Echos 7 and 12, respectively
}
print_r( $array ); //Now equals array( '0' => 7, '1' => 12 )
//Normal Method
foreach( $array as $value ) {
$value += 2; //Add 2 to each value
echo $value; //Echos 7 and 12, respectively
}
print_r( $array ); //Still equals array( '0' => 5, '1' => 10 )
References are faster, but not if you are planing on modifying the values while keeping the original array intact.
use
session_start();
$_SESSION['question'] = $que;
&que = array(an array of your 10m question s);
when your want to call it on another page to get a line up of your questions, use
while (list($key, $value) = each($_SESSION)) {
#Echo the questions using $key
echo "Here is a list of your questions";
echo "<br/>";
while (list($key2, $value2) = each($_SESSION)) {
#$value2 show's name for the indicated ID
#$key2 refers to the ID
echo "<br/>";
echo "Question: ".$value2." ";
echo "<br/>";
}
echo "<br/>";
}
OR you can also use
print_r;

How to assign variable dynamically to php list function

What I am doing that I want to generate a list based on how many items are in an array, so I have counted the items and loop over them, create a number based var and construct a string $var which contains $a1,$a2.... and assigns the $var to list list($var)
and tried to access $a1 but it gives me the error "Undefined variable: a1"
Is there any other way to do it?
Here is my code:
$arr = array('1','2','3');
$listsize = count($arr);
$var='';
for($i=1;$i<=$listsize;$i++){
$var.='$a'.$i;
if($i!=$listsize){
$var.=',';
}
}
list($var) = $arr;
echo $a1;
What you are looking for is variable variables.
In PHP, you can dynamically assign variables names (not just values).
Here is an example:
$foo = "Hello" . 1;
# In this line, I am taking the value of the variable $foo (Hello1) and
# using that as as a variable name. This is equivalent to
# $Hello1 = "World", except the variable is dynamic (hence variable variables).
$$foo = "World";
print $Hello1; # This will print World
Why not use extract()?
Try this:
$values = array('1','2','3');
$variables = array();
$length = count($values);
$key = 'a1';
for ($i = 0; $i < $length; $i++){
$variables[$key] = $values[$i];
$key++;
}
extract($variables);
echo $a1, $a2, $a3;
You can solve your problem without loops. Array $as is filled with your data, that has keys a1 to aX:
$arr = array('1', '2', '3', 'test', true, 4.56);
$keys = array_map(function($n) { return "a$n"; }, range(1, count($arr)) );
$a = array_combine($keys, $arr);
Array $as has keys and values like output bellow:
Array
(
[a1] => 1
[a2] => 2
[a3] => 3
[a4] => test
[a5] => 1
[a6] => 4.56
)
I advice you to use access to variables via array like $a['a3'], and not via variables like $a3.
If you would like to have $a1 ... $aX variables, extract array like:
extract($a);

Categories