Php use a string as variable name print_r - php

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.

Related

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 add letters of the name as array elements in php?

i am receiving the name from the $request in php.I want to do something like to add all the letters of the name in the array during the request e.g
$name=$_request['name'];
say $name='test';
i want to save it in an array in this format as array("t","e","s","t").
how can i do it ?
str_split is your friend.
$split_string = str_split($name);
It may be sufficient for you to access the string directly as an array, without the need to format the data:
$a = 'abcde';
echo $a[2];
Will output
c
However you won't be able to perform some array operations, such as foreach
see the php site
so it would be like
$name= 'test';
$arr1 = str_split($name);
would result in a array like:
Array
(
[0] => t
[1] => e
[2] => s
[3] => t
)
Here you go
$i = 0;
while(isset($name[$i])) {
$nameArray[$i] = $name[$i];
$i++;
}
Try this:
$letters = array();
for (int $i=0; $i < strlen($name); $i++){
$letters[] = $name[$i];
}
and you can access it with:
for (int $i=0; $i < strlen($letters); $i++){
$letters[$i];
}

Join string and variable to get another variable in PHP

Sorry if this has already been asked, but it's hard to search for it... I tried googlin this topic without success.
What I want to do is this:
$layoutColor = 2;
$colors1 = array ("F57171", "FACCCC");
$colors2 = array ("FF9900", "FFC66F");
$chosenTheme = "colors".$layoutColor;
echo $chosenTheme [0];
I want to join the $layoutColor variable with the word "colors" in order to get the variable $colors2.
How do I do that?
Thanks.
You're best off approaching this by just combining all your options into a single multi-dimensional array:
$layoutColor = 2;
$colors = array();
$colors[1] = array ("F57171", "FACCCC");
$colors[2] = array ("FF9900", "FFC66F");
$chosenTheme = $colors[$layoutColor];
echo $chosenTheme [0];
Try this:
<?php
$layoutColor = 2;
$colors1 = array ("F57171", "FACCCC");
$colors2 = array ("FF9900", "FFC66F");
$chosenTheme = "colors".$layoutColor;
echo ${$chosenTheme}[0];
Prints:
FF9900
I think you can simplify this using multi dimensional arrays:
$colors = array(
array ("F57171", "FACCCC"),
array ("FF9900", "FFC66F")
);
So...
echo $colors[0];
Or you can user variable variables:
$chosenTheme = ${"colors".$layoutColor};
You may try this
$layoutColor = 2;
$$colors2 = "colors".$layoutColor;
So you'll get $colors2 variable
print_r($colors2); // Array ( [0] => FF9900 [1] => FFC66F )
Notice the double $, that will keep the variable name in the variable.
Try with:
$layoutColor = 2;
$string = "color";
echo $$string.$layoutColor;
You need to use dynamic variables
$$chosenTheme = "colors".$layoutColor;
then access the array by using this variable
$chosenTheme
This might not be an answer to your question but, depending on your specific context, try something like this:
$layoutColor = 2;
$colors = array (
Array("F57171", "FACCCC"),
Array ("FF9900", "FFC66F")
);
echo $colors[$layoutColor][0];
A multi dimensional array is a lot easier to read

Remove Array value

[0] => LR-153-TKW
[1] => Klaten
[2] => Rectangular
[3] => 12x135x97
I have an array looking like this. and I want to completely remove 12x135x97 to the mother array so how would i do this?
You can use unset($arr[3]);. It will delete that array index. Whenever you want to delete an array value, you can use PHP unset() method.
As you were asked into your comment:
basically i just want to remove all index that have "X**X" this pattern digit 'x' digit
Here is the code that you can use:
$arr = array("LR-153-TKW", "Klaten", "Rectangular", "12x135x97", "xxxx");
$pattern_matched_array = preg_grep("/^[0-9]+x[0-9]+x[0-9]*/", $arr);
if(count($pattern_matched_array) > 0)
{
foreach($pattern_matched_array as $key => $value)
{
unset($arr[$key]);
}
}
print_r($arr);
PHP has unset() function. You can use it for deleting a variable or index of array.
unset($your_var[3]);
See http://php.net/manual/en/function.unset.php
You have many options:
if you know the array key then you can do this
unset($arrayName[3]);
or if it's always at the end of your array
array_pop($arrayName);
this will remove the last value out of your array
Use unset, to find it you can do this:
for($i = 0; $i < count($array); $i++){
if($i == "12x135x97"){
unset($array[i]);
break;
}
}
Unless you know the key, in which case you can do:
unset($array[3]);
its not the most time efficient if you array is thousands of items long, but for this job it will suffice.
To turn it into a method, would make for better coding.
function removeItem($item){
for($i = 0; $i < count($array); $i++){
if($i == $item){
unset($array[i]);
break;
}
}
return $array;
}
and call it like:
removeItem("12x135x97");

How to access php variable using concatenation [duplicate]

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
?>

Categories