"Large multiple variable echo's" way to make simpler? - php

Say I am echoing a large amount of variables in PHP and I wont to make it simple how do i do this? Currently my code is as follows but it is very tedious work to write out all the different variable names.
echo $variable1;
echo $variable2;
echo $variable3;
echo $variable4;
echo $variable5;
You will notice the variable name is the same except for an incrementing number at the end. How would I write a script that prints echo $variable; so many times and adds an incrementing number at the end to save me writing out multiple variable names and just paste one script multiple times.?
Thanks, Stanni

You could use Variable variables:
for($x = 1; $x <= 5; $x++) {
print ${"variable".$x};
}
However, whatever it is you're doing there is almost certainly a better way: probably using Arrays.

I second Paolo Bergantino. If you can use an array that would be better. If you don't how to do that, here you go:
Instead of making variables like:
$var1='foo';
$var2='bar';
$var3='awesome';
... etc... you can make a singe variable called an array like this:
$my_array = array('foo','bar','awesome');
Just so you know, in an array, the first element is the 0th element (not the 1st). So, in order to echo out 'foo' and 'bar' you could do:
echo $my_array[0]; // echoes 'foo'
echo $my_array[1]; // echoes 'bar'
But, the real benefits of putting value in an array instead of a bunch of variables is that you can loop over the array like this:
foreach($my_array as $item) {
echo $item;
}
And that's it. So, no matter how many items you have in your array it will only take those three lines to print them out. Good luck you with learning PHP!

Use dynamic variable names:
for($i=1; $i < 6; $i++) echo ${'variable'.$i}

Related

How do you print a variable in PHP that's either one element of an array, or the whole variable if it's not an array

Say I have $exampleVariable, which I want to print. $exampleVariable may be an array, in which case I have this set up to get the right array element, which I can then print with print $exampleVariable[$i].
if ($_GET) {
$i = array_search($_GET["exampleQueryString"], $exampleVariable);
} elseif (is_array($exampleVariable)) {
$i = 0;
} else {
$i = "";
}
My problem is that last else, if $exampleVariable is NOT an array, because then I get print $exampleVariable[] which doesn't work. So is there something I can put as $i to print the whole variable?
Alternatively, I considered including the brackets in $i, so I'd have for example $i = [0];, but in that case I don't know how I'd print it. $exampleVariable$i certainly won't work.
I have a good number of variables besides $exampleVariable I'll need to print, all with the same $i or lack thereof, so I'd like to not have to do anything longwinded to set each of them up individually.
This sounds way more complicated than I feel like it should, so hopefully it makes sense!
You can always do a nifty thing that is called type casting. That means, that you can always make a variable an array even if it is not, by prepending its name by (array):
$exampleVariable = (array)$exampleVariable;
So you don't need three if branches at all:
if ($_GET) { 
$i = array_search($_GET["exampleQueryString"], $exampleVariable);
} else {
$i = 0;
$exampleVariable = (array)$exampleVariable;
}
You could apply the (array) cast, which will have no effect if the target is already an array:
$i = array_search($_GET["exampleQueryString"], (array)$exampleVariable);

PHP- concatenate string with iterator to get original variable name

I have 20 variables with name $encode1,$encode2....,$encode20.
Now, I want to print these variable in the for loop by combining $encode.$1 to achive variable $encode1.
Loop example:
for($i =1;$i<=20;$i++)
{
$echo = $encodedImage.$i; => What to do here?
}
How could I access the names by using iterator?
Plus, I don't want to create an array. I just want to access them directly dynamically.
I haven't found any answer on stackoverflow regarding this topic. If there is any, please share me the link. Thanks!
using variables variable to achieve such a approach
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:
for($i = 1; $i <= 20; $i++) {
$myVariable = "encoded" . $i;
echo $$myVariable;
}
Use it this way.
Try this code snippet here
<?php
$encoded1=10;
$encoded2=20;
$encoded3=30;
for($i =1;$i<=3;$i++)
{
echo ${"encoded".$i};
}

php array syntax ${ is confusing me

I create a $values array and then extract the elements into local scope.
$values['status'.$i] = $newStatus[$i];
extract($values);
When I render an html page. I'm using the following
<?php if(${'status'.$i} == 'OUT'){ ?>
but am confused by what the ${ is doing and why $status.$i won't resolve
$status.$i means
take value of $status variable and concatenate it with value of $i variable.
${'status'.$i} means
take value of $i variable, append id to 'status' string and take value of a variable 'status'.$i
Example:
With $i equals '2' and $status equals 'someStatus':
$status.$i evaluated to 'someStatus' . '2', which is 'someStatus2'
${'status'.$i} evaluated to ${'status'.'2'} which is $status2. And if $status2 is defined variable - you will get some value.
I wanted to add to the accepted answer with a suggested alternate way of achieving your goal.
Re-iterating the accepted answer...
Let's assume the following,
$status1 = 'A status';
$status = 'foo';
$i = 1;
$var_name = 'status1';
and then,
echo $status1; // A status
echo $status.$i; // foo1
echo ${'status'.$i}; // A status
echo ${"status$i"}; // A status
echo ${$var_name}; // A status
The string inside the curly brackets is resolved first, effectively resulting in ${'status1'} which is the same as $status1. This is a variable variable.
Read about variable variables - http://php.net/manual/en/language.variables.variable.php
An alternative solution
Multidimensional arrays are probably an easier way to manage your data.
For example, instead of somthing like
$values['status'.$i] = $newStatus[$i];
how about
$values['status'][$i] = $newStatus[$i];
Now we can use the data like,
extract($values);
if($status[$i] == 'OUT'){
// do stuff
}
An alternative solution PLUS
You may even find that you can prepare your status array differently. I'm assuming you're using some sort of loop? If so, these are both equivalent,
for ($i=0; $i<count($newStatus); $i++){
$values['status'][$i] = $newStatus[$i];
}
and,
$values['status'] = $newStatus;
:)

Dumping many variables in PHP

I assure this is a very common situation when you have to test variables (and they are many!), just like this example (I only named vars like this for less-effort-writing sake):
$variable0='red';
$variable1='blue';
$variable2='green';
$variable3='pink';
$variable4='purple';
$variable5='hellow';
$variable6='foo';
$variable7='bar';
$variable8='hi';
$variable9='bye';
echo
'$variable0='.$variable0.'<br>
$variable1='.$variable1.'<br>
$variable2='.$variable2.'<br>
$variable3='.$variable3.'<br>
$variable4='.$variable4.'<br>
$variable5='.$variable5.'<br>
$variable6='.$variable6.'<br>
$variable7='.$variable7.'<br>
$variable8='.$variable8.'<br>
$variable9='.$variable9;
My question is: is there a better way to make this echoing / dumping / printing easier?
Of course, there are other ways of doing the very same presidiary work:
$x=
'$variable0='."$variable0\n".
'$variable1='."$variable1\n".
'$variable2='."$variable2\n".
'$variable3='."$variable3\n".
'$variable4='."$variable4\n".
'$variable5='."$variable5\n".
'$variable6='."$variable6\n".
'$variable7='."$variable7\n".
'$variable8='."$variable8\n".
'$variable9='."$variable9"
echo nl2br($x);
Or:
$x=<<<HEREDOC
\$variable1=$variable1
\$variable2=$variable2
\$variable3=$variable3
\$variable4=$variable4
\$variable5=$variable5
\$variable6=$variable6
\$variable7=$variable7
\$variable8=$variable8
\$variable9=$variable9;
HEREDOC;
echo nl2br($x);
But maybe PHP has a function to make this easier?
By the way, all 3 solutions above echoes the very same:
$variable1=blue<br>
$variable2=green<br>
$variable3=pink<br>
$variable4=purple<br>
$variable5=hellow<br>
$variable6=foo<br>
$variable7=bar<br>
$variable8=hi<br>
$variable9=bye;
Introducing compact:
var_dump(compact('foo', 'bar', 'baz'));
Note though that I explicitly used three very different variables: $foo, $bar and $baz.
If you actually do literally have $foo1, $foo2 etc, you're really really looking to use an array instead. Dumping that would be trivial too:
$foo = array();
$foo[0] = 'bar';
$foo[1] = 'baz';
var_dump($foo);
In general, if you have too many variables floating around, your scope is probably too big and you should refactor everything into a number of smaller functions, or your algorithm is more complex than it needs to be, or you should be using arrays or other data structures instead.
get_defined_vars() would be able to do so. Might be overkill (all accessable vars will be shown):
print_r( get_defined_vars() );
Return Values: A multidimensional array with all the defined variables*.
*In a function it will only show the local $vars, and those defined as global.
Note: This does exactly what you're looking for, but the array methods mentioned in other answers would be a better fit logical-wise, see below:
A better way for you to set the values is with an array, this way you 'group' multiple values together:
$color[] = 'red'; // will automatically start with key=0
$color[] = 'blue'; // key=1
$color[] = 'green';// key=2 etc
print_r( $color );
echo $color[1]; // Blue, same as your echo $variable1;
You can declare your variables as keys from an array instead
$myarray=Array();
$myarray['variable0']='red';
$myarray['variable1']='blue';
$myarray['variable2']='green';
$myarray['variable3']='pink';
$myarray['variable4']='purple';
$myarray['variable5']='hellow';
$myarray['variable6']='foo';
$myarray['variable7']='bar';
$myarray['variable8']='hi';
$myarray['variable9']='bye';
and print them all with
echo '<pre>';
print_r($myarray);
echo '</pre>';
then, in case you still need to use them as separate variables, doing
extract($myarray)
will create $variable0 to $variable9 in the global context.
If you know the upper and lower bounds and all the variables have a similar name you could do the following:
for ($i = 0; $i < $end; ++$i) { echo ${'value_name'. $i}; }
Try refactor your code and use arrays
Then you can do print_r or var_dump
This should give you the output your looking for:
function get_var_name($var) {
foreach($GLOBALS as $var_name => $value) {
if ($value === $var) {
return $var_name;
}
}
return "Variable name not found";
}
function miracle_var_dump($valuesToDump) {
//For each variable in the $valuesToDump array, print the name and value
for($i = 0; $i < count($valuesToDump); $i++) {
echo(get_var_name($valuesToDump[i]) . "=" . $valuesToDump[i] . "<br/>");
}
}
//Making a call to dump the variables
miracle_var_dump(array($variable0,$variable1,$variable2,$variable3,$variable4,$variable5,$variable6,$variable7,$variable8,$variable9))
Function get_var_name gets the variable name given the variable (taken from one of Jeremey Rutins awsners).
//let your variables like this
$variable0='red';
$variable1='blue';
$variable2='green';
//an array to keep all the variable names
$var_names=array();
$var_names[]='$variable0';
$var_names[]='$variable1';
$var_names[]='$variable2';
//etc...
print_var_name($var_names);
function print_var_name($var_names) {
//loop through the array and dump them if they are in $GLOBALS
foreach($GLOBALS as $var_name => $value) {
if (in_array('$'.$var_name,$var_names)) {
echo $var_name;
var_dump($value);
}
}

php for loop variable names

i got a code of 100-200 rules for making a table. but the whole time is happening the same.
i got a variable $xm3, then i make a column . next row, i got $xm2 and make column. next row, i got $xm1 and make column.
so my variables are going to $xm3, $xm2, $xm1, $xm0, $xp1, $xp2, $xp3.
is there a way to make a forloop so i can fill $xm and after that a value from the for loop?
In this kind of structure you'd be better off using an array for these kinds of values, but if you want to make a loop to go through them:
for($i = 0; $i <= 3; $i++) {
$var = 'xm' . $i
$$var; //make column stuff, first time this will be xm0, then xm1, etc.
}
It is not fully clear what you are asking, but you can do
$xm = 'xm3';
$$xm // same as $xm3
in PHP, so you can loop through variables with similar names. (Which does not mean you should. Using an array is usually a superior alternative.)
As far as I am aware using different variable names is not possible.
However if you uses arrays so as below
$xm[3] = "";
$xm[2] = "";
$xm[1] = "";
$xm[0] = "";
or just $xm[] = "";
Then you can use a for each loop:
foreach($xm as $v) { echo $v; }
Edit: Just Googled and this is possible using variable names but is considered poor practice. Learn and use arrays!
You can do this using variable variables, but usually you're better off doing this sort of thing in an array instead.
If you're positive you want to do it this way, and if 'y' is the value of your counter in the for loop:
${'xm' . $y} = $someValue;
You can easily do something like this:
$base_variable = 'xm';
and then you can make a loop creating on the fly the variables;
for example:
for ($i=0; $i<10; $i++)
{
$def_variable = $base_variable . $i;
$$def_variable = 'value'; //this is equivalent to $xm0 = 'value'
}

Categories