I'm a bit confused about variable variables.
What I like to do is print the value of $var1, $var2 and $var3:
$var1 = 'a';
$var2 = 'b';
$var3 = 'c';
$i = 1;
while ( $i <=3 ) {
echo $var.$i;
$i++;
}
I know $var.$i; is not correct, but I think it shows what I would like to achieve; the while-loop should change it to $var1, $var2 and $var3;
I've tried the following:
$var1 = 'a';
$var2 = 'b';
$var3 = 'c';
$i = 1;
while ( $i <=3 ) {
$current_var = 'var'.$i;
$current_var = $$current_var;
echo $current_var;
$i++;
}
But that doesn't work. I think because $var1, $var2 and $var3 are recreated in the while-loop instead of using the actual value. Not sure if that's correct, but that the only thing I can think of.
Try this instead:
echo ${"var".$i};
Curly braces can resolve to variable names without having to use the dollar-dollar approach.
See: Variable Variables in PHP
Try this one.
<?php
$var1 = 'a';
$var2 = 'b';
$var3 = 'c';
$i = 1;
while ( $i <=3 ) {
echo ${'var'.$i};
$i++;
}
?>
Are you trying to do something like this. Then use array
$my_data = array();
$my_data[1] = 'a';
$my_data[2] = 'b';
$my_data[3] = 'c';
// Method 1
$i = 1;
while ($i <= 3) {
echo $my_data[$i];
$i++;
}
// Method 2
foreach ($my_data as $data) {
echo $data;
}
// Output
abc
abc
Related
I am trying to create a dynamic variable. I have a loop and I want it to loop through the records and create a variable for each record. My code:
$ct = 1;
foreach ($record as $rec){
$var.$ct = $rec['Name'];
$ct = $ct + 1;
}
echo $var1;
When I try to use the above code, it gives me an error saying the $var1 variable doesn't exist/undefined? Is it possible in PHP to create dynamic variables like the above example. If so, what am I doing wrong?
You're looking for variable variables.
Create the variable name as a string, and then assign it:
$ct = 1;
foreach( $record as $rec )
{
$name = 'var'.$ct;
$$name = $rec['Name'];
$ct++;
}
echo $var1;
It would be much better to create an array, though:
$names = [ ];
foreach( $record as $rec )
{
$names[] = $rec['Name'];
}
echo $names[0];
You can use different syntax with {}
$ct = 1;
foreach ($record as $rec){
${'var' . $ct++} = $rec['Name'];
}
echo $var1;
Although isn't it better just to use an array?
Working fiddle
You can with a double $.
$var = "variable";
$$var = "test";
echo $variable;
//echoes "test"
in your example:
$ct = 1;
foreach ($record as $rec){
$varname = "var" . $ct;
$$varname = $rec['Name'];
$ct = $ct + 1;
}
echo $var1;
Please try this, let me know if it works for you.
I use a prefix with the dynamic variable.
$ct = 1;
$prefix = 'var';
foreach ($record as $key=>$rec){
$temp = $ct;
$ct = $prefix.$ct;
$$ct = $rec;
$ct = $temp + 1;
}
echo $var1;
You can do that using array easily. But if you really want it to be in dyanamic vairable individually, in that case also , I would like to suggest you to get help in array way. This way, you can track you variables.
In the below mentioned way, you event don't need to take a extra variable like $ct. Just an array $var and applying extract method on it after the loop will do the trick.
$var = [];
foreach( $record as $k => $rec )
{
$var['var'.$k] = $rec['Name'];
}
extract($var);
echo $var0; //or $var_1 or $var_2
If they are same do nothing, if they are different do the bottom and make them same. Whole script is in a loop but the loop is only doing else. Like it is not checking for conditions. What am I doing wrong?
for ($int = 0; $int < 10, $int+1){
$array = $getarray();
foreach ($array as $array){
$var1 = $array->id;
$var2 = null;
if ($var1 == $var2){
echo ('skip');
}else{
echo '<br>'.$var1.'<br>';
ob_flush();
$var2 = $var1;
}
}
}
Initially var2 is null and var1 gets string value. So it performs else and var2 gets the var1 string.
Next Loop if var1 has not changed, it will equal var2. So it does nothing and skips
I don't understand the logic of these loops but this is how you should do it:
for ($int = 0; $int < 10, $int++) {
/*
* I suppose getarray() is a function.
* If you have a variable $getarray containing the name of another function
* then you should change getarray() to $getarray()
*/
foreach (getarray() as $array) {
if (is_null($array->id)) {
echo ('skip');
} else {
echo "<br />{$array->id}<br />";
ob_flush();
}
}
}
Your code does not work properly, as how many times your loop will execute, your $var2 will become null, so not a single time you will be reached at the point where your $var1 & $var2 values are same.
So instead please try the following code.
for ($int = 0; $int = 10; $int+1){
$array = $getarray();
$var2 = null;
foreach ($array as $array){
$var1 = $array->id;
if ($var1 == var2){
echo ('skip');
}else{
echo '<br>'.$var1.'<br>';
ob_flush();
$var2 = $var1;
}
}
}
I tried to create this variable:
<?php
echo ${"product['id']"};
?>
But it is wrong. Who can help with right syntax?
<?php
echo $product['id'];
?>
You don't need to wrap the variable into string if you want to print just one variable. Php will do it for you
If you need to generate variable name in code you can try this:
$var1 = 'hello';
$var2 = ' ';
$var3 = 'world';
for ($i = 1; $i <= 3; ++$i) {
$varName = 'var'.$i;
print $$varName; // use $$ to use string as a variable name
}
Result will be hello world
This is the equivalent for previous example
$var1 = 'hello';
$var2 = ' ';
$var3 = 'world';
$vars = array(1, 2, 3);
foreach ($vars as $var) {
$varName = 'var'.$var;
print $$varName;
}
I'm looking for something like this:
$a = array();
$var1 = 'var1';
$var2 = 'var2';
$i = array_push($a, $var1);
$j = array_push($a, $var2);
echo $i;
echo $j;
The expected output would be:
0
1
I want to know the index of the object I just inserted, to be able to find it quickly afterwards. I think array_push gives me the size of the resulting array, not the index for the recently inserted element
array_push return new number of elements in the array, so decrement the return value by 1
Try this:
$a = array();
$var1 = 'var1';
$var2 = 'var2';
$i = array_push($a, $var1) - 1;
$j = array_push($a, $var2) - 1;
echo $i;
echo $j;
function my_push_array(&$array, $value){
$array[] = $value;
end($array);
return key($array);
}
$a = ['h','e','l','l'];
echo my_push_array($a, 'o'); //returns 4
I have numerous variables and I need to print a numeric value for how many of these variables are equal to zero:
$var1 = '2';
$var2 = '0';
$var3 = '4';
//check how many variables = 0
$zeros = ?
//should be a numeric value this example should print '1'
echo $zeros
Thanks for any suggestions!
This gets a list of all defined variables, and counts how many are === 0 and excludes the $_GET, $_POST, and $_COOKIE globals.
If you define this code in a function, then only the variables in that scope are counted.
<?php
$value = 0;
$var = 1;
$test = false;
$nine = 0;
$zero = 9;
$zeroes = 1; // set to 1 so we don't count this
$vars = get_defined_vars();
foreach($vars as $var) {
if (is_array($var) && (
isset($var['_GET']) || isset($var['_POST']) ||
isset($var['_COOKIE']))
) {
continue; // don't count superglobal arrays
}
if ($var === 0) $zeroes++;
}
$zeroes -= 1; // subtract the initial value
echo "There are $zeroes zero values."; // There are 2 zero values.
EDIT: It could be modified to be a function that would work recursively if you needed to check the values of arrays for example. You could call it from the global scope like this:
$zeroes = countZero(get_defined_vars());
And then the function could detect arrays and call itself until it has searched all vars.
if($var1 == 0) $zeros++; repeat for var2, 3, etc.
Use variable variables to generate variables from a string if they all follow the varX pattern where X is a number.
$var1 = '2';
$var2 = '0';
$var3 = '4';
$zeros = 0;
for($i = 1; $i <= 3; $i++) {
$var = ${'var' . $i};
if($var == 0) $zeros ++;
}
echo $zeros;
I do not understand the purpose of what you are trying to achieve here and maybe I am misunderstanding the need but the following yet simple code does it:
$var1 = '2';
$var2 = '0';
$var3 = '4';
$zeros = ($var1 =='0')?1:0 + ($var2 =='0')?1:0 + ($var3 =='0')?1:0;
echo $zeros
Basically I nested ternaly conditional expressions instead of using regular if then elses.
I put all of my variables into an array, looped with foreach and added to the $zeros variable:
$values = array('0' => $var1, '1' => $var2, '2' => $var3);
$zeros = 0;
foreach($values as $v) {
if($v === '0')
$zeros++;
}
echo $zeros;
I found this was an easy solution, thanks for the input though!