php for loop variable names - php

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

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

Passing variable variables into if statement - php

I have a series of variables in php:
move1A = $row['column'];
move2A = $row['column'];
move3A = $row['column'];
etc.
I want to create a variable that will represent these variables and check if it is NULL. I have spent quite a bit of time looking, and although I believe that variable variables may be the key to my problem. So far I have tried:
$current_move_check = 'move'.$moveCounter.'A';
and
$current_move_check = '$move'.$moveCounter.'A';
Neither seem to work. Any suggestions for making something like this work? Thanks!
UPDATE:
So I'm trying to loop the moveXA variables based on user input and I need to run different script whether it is null or set.
I thought that:
elseif (!$$current_move_check) {
and
elseif ($$current_move_check) {
would work but they seem to not be outputting as expected.
Considering your update, I'd really suggest you to use an array, rather than the variable variables trick. Your code would makes more sense and be easier to maintain :
$count = 0;
$moveA[++$count] = $row['column'];
$moveA[++$count] = $row[...];
$moveA[++$count] = $row[...];
...
foreach ($moveA as $key => $value) {
if ($value) { // = $$current_move_check
} else { // = !$$current_move_check
}
}
As #MatsLindh pointed out in its comment : "Variable variables are never a good idea. Unless you know when it makes sense to break that rule, don't."
$current_move_check = 'move'.$moveCounter.'A';
echo $$current_move_check;
now you can check this as well like
if($$current_move_check!=NULL)
{
// do your code
}

PHP How to compact my variables into a FOR loop?

I have a list of variables which I am using for some PHP functions. I know I can simplify this code but I am not really sure how. I have tried for(){} loops but haven't figured out how to make the result usable.
HERE ARE MY VARIABLES
$saveData_1 = post_data($url_1);
$saveData_2 = post_data($url_2);
$saveData_3 = post_data($url_3);
$saveData_4 = post_data($url_4);
$saveData_5 = post_data($url_5);
$saveData_6 = post_data($url_6);
$saveData_7 = post_data($url_7);
$saveData_8 = post_data($url_8);
$saveData_9 = post_data($url_9);
$saveData_10 = post_data($url_10);
$saveData_11 = post_data($url_11);
$saveData_12 = post_data($url_12);
$saveData_13 = post_data($url_13);
$saveData_14 = post_data($url_14);
$saveData_15 = post_data($url_15);
$saveData_16 = post_data($url_16);
$saveData_17 = post_data($url_17);
$saveData_18 = post_data($url_18);
$saveData_19 = post_data($url_19);
$saveData_20 = post_data($url_20);
HERE IS WHAT I HAVE TRIED
for($i = 0; $i<20; $i++) {
$saveData = '$saveData_'.$i;
$postData = 'post_data($url_'.$i.')';
print($saveData. '=' .$postData. ';');
}
This works for the most part, it prints out my list of variables. But what I don't know, is how to make this usable so instead of printing them to the page being displayed in the browser they will be instead be "printed" to my php script.
Basically my goal is to write the Variables of above without having to actually write a new variable each time.
If I understand what you're asking correctly, you want to have actual "variables" that you can use, such as $saveData_16, but don't want to type each one out?
If that's the case, you can what's called a variable-variable:
$varName = 'saveData_16';
$postName = 'url_16';
$$varName = post_data($$postName);
Note the double $$ prefixing the variable's name.
This can be dropped into a loop with:
for ($i = 0; $i < 20; $i++) {
$varName = 'saveData_' . $i;
$postName = 'url_' . $i;
$$varName = post_data($$postName);
}
Variable-variables can be tricky to remember and a nuisance to keep up with, especially if they contain similar names/values as existing variables. If they do, they can easily overwrite an important variable in your code. If this is a potential issue, you should probably avoid them.
An alternative to variable-variables, but on the same topic, if your values really do come from $_POST (based on the function-name post_data()), you can look into PHP's extract() function which performs the same "extraction" for you:
extract($_POST);
I would recommend against using extract() unless you're very clear on what's needed though. It can easily overwrite other variables that use the same name as a posted field. It does provide an optional second-parameter named $extract_type that is a flag specifying the behavior of the extract and, through this, you can tell it to not overwrite existing variables:
extract($_POST, EXTR_SKIP);
Again though, this can cause headaches by simply forgetting the optional flag - so I would avoid this function if this is a risk.
As an additional alternative, you could store the results into an array and use the array as-is. I personally support this method and, if you use strings as your array indexes, it can be just-as-readable as using a variable (and more-readable than a variable-variable).
If you're currently using $_POST, well, you should be all set - it's already in array form. However, if you're obtaining your data in a different method you can always build your own array with:
// build your array
$saveData = array();
for ($i = 0; $i < 20; $i++) {
$urlName = 'url_' . $i;
$saveData['url_' . $i] = post_data($$urlName);
}
// access a value
echo $saveData['url_4'];
I'm not 100% sure what your $url_# variables are, so I've kept that as a variable-variable in the array example; if it's just a string, you could replace it with the string instead.
You need to use arrays. I will type up an example and add it to this comment. But what you want to use is an array variable. One array can hold all this and you can iterate (loop) through it easily.
Here ya go:
<?php
/* what the heck? You need arrays ;-)
$saveData_1 = post_data($url_1);
$saveData_2 = post_data($url_2);
$saveData_3 = post_data($url_3);
$saveData_4 = post_data($url_4);
$saveData_5 = post_data($url_5);
$saveData_6 = post_data($url_6);
$saveData_7 = post_data($url_7);
$saveData_8 = post_data($url_8);
$saveData_9 = post_data($url_9);
$saveData_10 = post_data($url_10);
$saveData_11 = post_data($url_11);
$saveData_12 = post_data($url_12);
$saveData_13 = post_data($url_13);
$saveData_14 = post_data($url_14);
$saveData_15 = post_data($url_15);
$saveData_16 = post_data($url_16);
$saveData_17 = post_data($url_17);
$saveData_18 = post_data($url_18);
$saveData_19 = post_data($url_19);
$saveData_20 = post_data($url_20);
*/
$saveData = array(); // just a formality. You don't need to delcare variable types in PHP.
for ($i = 1; $i < 21; $i++) {
$var = 'url_'.$i;
$saveData[$i] = post_data($$var);
}
// now all your stuff is in $saveData
// what's in savedata 20? this is:
echo $saveData[20];
// you could skip all of this and just use the $_POST superglobal
$_POST[$url_20]
// I'm curious to see what you are doing, because this process should be re-thought.

Categories