composed variable after Object Operator in PHP - php

How can I build a composed variable while creating a variable in PHP?
(Sorry I'm not sure how to call the different elements)
This is what I'm trying to do:
$language = 'name_'.$this->session->userdata('site_lang');
for ($i=1;$i<=3;$i++) {
$data = $arraydata->$language_.$i; // problem is here
}
I would like $language_.$i to be equivalent to name_english_1, next loop name_english_2... The same way I built $language

If you want to use an expression in a computed property, you have to put the expression in braces. Also, you need to put the underscore in quotes.
$data = $arraydata->{$language."_".$i};
However, I suggest you redesign your data structure. Instead of having separate name_LANG_i properties, make a single name property whose value is a multi-dimensional array.
$lang = $this->session->userdata('site_lang');
for ($i=1;$i<=3;$i++) {
$data = $arraydata->name[$lang][$i];
// do something with $data
}
Whenever you find yourself using variable variables or variable properties, it's almost always a sign that you should be using an array instead.

First construct the field name and then use it for accessing the field value from the object $arraydata. So your code should be like this:
$language = 'name_'.$this->session->userdata('site_lang');
for ($i = 1; $i <= 3; $i++) {
$var = "{$language}_{$i}";
$data = $arraydata->$var;
// echo $data;
}

Related

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

Is there a function to get all the variables in a given php string?

I have a script which includes a double-quoted string (used to make an html table, if it makes a difference) that incorporates about a dozen variables. Each of those variables is modified by a while loop. I would like to push each set of values to a multidimensional array on each iteration of the loop. Right now I could do
array_push($my_array, $var1, $var2, $var3, ...);
but that is awkward.
Is there a way to just dump all the variables in this string into my array, something like:
array_push($my_array, get_vars_from_string($string));?
(Obviously it would have been wonderful if the variables used in the script were in an array to begin with, but I didn't write the original and changing that would require too many changes to the structure of the program.)
By "variables inside a string" I mean: $table = "<td>$var1</td><td>$var2</td><funky stuff with subheadings> stuff..."
function get_vars_from_string($param)
{
$arrfromstring=explode('$',$param);//or tokenize here
$ret=array();//return value
//then do the formatting and get the names of the variables,this can be done by some other functions too
foreach($arrayfromstring as $key)
array_push($ret,${$key});//this is the part you are looking for.
}
You will understand what i mean by the the tokenizing part I think. The interesting part is the ${$key}. An example.
To get variables from string, you can use token_get_all(), but you have to use string not processed by php, but raw line of code that assigns this string to variable.
Proof of concept code with bad practices:
<?php
$string_vars = array();
$double_quote_started = false;
$all_vars = array();
$table = "";
$var1 = 5;
$var2 = -5;
while($var1-- && $var2++) {
// note single quotes, this does not evaluate variables but treats everything as string
$table_str = <<<'EOT'
$table .= "<td>$var1</td><td>$var2</td><td>funky stuff</td>";
EOT;
//evaluate the line as it was earlier
eval($table_str);
// since this is is first iteration, let's search our string for them
if (empty($string_vars)) {
foreach(token_get_all("<?php " . $table_str) as $token) {
if (is_array($token) && $token[0] == T_VARIABLE && $double_quote_started) {
$string_vars[] = substr($token[1],1);
} elseif ($token === '"') {
$double_quote_started = !$double_quote_started;
}
}
}
$this_iteration = array();
foreach($string_vars as $var){
// variable variable to get content of variable
$this_iteration[$var] = $$var;
}
// save this iteration vars
$all_vars[] = $this_iteration;
}

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.

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