PHP Loop Dynamic Variable - php

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

Related

Call an existing php variable by concatenating two strings

I have these seven php variables:
$dataA = 1;
$targetA = 2;
$dataB = 3;
$targetB = 4;
$dataC = 5;
$targetC = 6;
results = array('A','B','C');
I would like to loop through the results array and pass the corresponding variables to a function.
foreach($results as $value) {
$data = '$data'.$value;
$target = '$target'.$value;
buildOutput('$data'.$value,'$target'.$value);
}
// example, first time thru, wish to pass $dataA variable and $targetA variable
function buildOutput($data,$target) {
echo "data=$data,target=$target<br>"; // echo's strings "$dataA" and "$targetA"
}
I cannot figure out how to declare the variables. Or if this is even possible.
I have more than just $data and $target variables, but I simplified down to two for the question.
I would not recommend using it, but try this:
$dataA = 1;
$targetA = 2;
$dataB = 3;
$targetB = 4;
$dataC = 5;
$targetC = 6;
$results = array('A','B','C');
foreach($results as $value) {
buildOutput(${'data'.$value}, ${'target'.$value});
}
function buildOutput($data, $target) {
echo "data=$data,target=$target<br>";
}

Build string on one line PHP

I want to build a combination of numbers and letters separated by - (minus sign). i.e 1-R-3. The first number are in an array called $Points ,the letters are stored in a array called $Color and the last number is in a third array called $Points2;
$Points = [1,2,3,4];
$Color = [R,B,V,Y];
$Points = [1,2,3,4];
I want the result to be one one row 1-R-1, 2-B-2 and so on. Now the result outputs as:
1
(minus sign)
R
(minus sign)
3
`
$Bind = "-";
$foo = $Points[0] . $Bind . $Points[1];
I have tried to convert the integer to a string by (String) but have not worked.
Can somebody help me to get the result on one line? I bet i'm missing something easy!
EDIT: The format in the arrays where incorrect since I forgot ->plaintext when doing my web-scraping.
/U
$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
foreach ($Points as $point=>$value) {
echo $value . '-' . $Color[$point] . '-' . $value . PHP_EOL;
}
Note that the values in the $Color array need to be in quotes to avoid errors.
You have two arrays called $Points, so I've renamed one.
This just combines the three arrays by using foreach and using the key of each element and using it to access the other arrays at the same index...
$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
$Points1 = [1,2,3,4];
$bind = "-";
foreach ( $Points as $key => $val ) {
echo $val.$bind.$Color[$key].$bind.$Points1[$key].PHP_EOL;
}
This may be occurring because of the tabs or carriage return:
<?php
$points = [1,2,3,4];
$colors = ['R','B','V','Y'];
$bind = '-';
$foo = [];
for ($x = 0; $x <= 3; $x++) {
$foo[$x] = $points[$x].$bind.$colors[$x].$bind.$points[$x];
}
foreach($foo as $value) {
echo $value.'<br>';
}
?>
Result:
1-R-1
2-B-2
3-V-3
4-Y-4
You can use php join function. For example:
$results = [];
for ($i = 0; $i < count($Points); $i++) {
$results[] = join('-', [$Points[$i], $Colors[$i], $Points2[$i]]);
}
// Now you have your combined values in $results array
var_export($results);
You can combine array into one string like
<?php
$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
$Points = [1,2,3,4];
$result='';
$bind='-';
foreach ($Points as $index => $value) {
$result .= $value .$bind . $Color[$index] . $bind . $value.PHP_EOL;
}
echo $result;
?>
DEMO

add numbers in an array with PHP

I want all of the elements in the array to be added together, but this doesn't seem to be working.
<?php
function mimic_array_sum($array) {
foreach($array as $total) {
$total = $total + $total;
}
return $total;
}
$var = array(1,2,3,4,5);
$total = mimic_array_sum($var);
echo $total;
?>
$total = $total + $total --> well, there's your problem...
The $total variable gets overwritten on each loop through the array.
Assign a separate variable for each number in the array, like so:
function mimic_array_sum($array) {
$total = 0;
foreach($array as $number) {
$total = $total + $number;
}
return $total;
}
$var = array(1,2,3,4,5);
echo mimic_array_sum($var);
Although the point of this is not clear to me... You might as well use the php-function array_sum...
$var = array(1,2,3,4,5);
echo array_sum($var);
$var = array(1,2,3,4,5);
$total = array_reduce(
$var,
function($sum, $value) {
return $sum + $value;
}
);
though why not simply use array_sum()?
You can use array_sum — Calculate the sum of values in an array
$var = array(1,2,3,4,5);
$total = array_sum($var);
echo $total;
<?php
function mimic_array_sum($array) {
$total = 0;
foreach($array as $elem) {
$total += is_numeric($elem) ? $elem : 0;
}
return $total;
}
$var = array(1,2,3,4,5);
$total = mimic_array_sum($var);
echo $total;
?>
<?php
$a = array(1,2,3,4,5);
echo "sum is:".array_sum($a);
?>
See Manual
Please try following, you have to take separate variable to do so. Or else you can use array_sum()
function mimic_array_sum($array) {
$test = 0;
foreach($array as $total) {
$test = intval($test) + intval($total);
}
return $test;
}
$var = array(1,2,3,4,5);
$total = mimic_array_sum($var);
echo $total;
?>

php - use variable variable in while loop

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

problem with declaring variable in php?

i have a variables like $srange0 , $srange1, $srange2 $srange3.
i am using to declare some value to each value using for loop.
for($i=0;$i<=3;$i++){
$srange.$i = $i;
}
but its not working ?
is there any alternative solution for this
for($i=0;$i<=3;$i++){
$var = 'srange'.$i;
$$var = $i;
}
But, whenever I see variables like that, I'd use an array instead.
Use an array:
$srange = array();
for ($i = 0; $i <= 3; ++$i)
$srange[$i] = $i;
For the purpose of this particular task, you can also do this:
$srange = range(0, 3);
That also builds the same array as my first code snippet.
The properway to add these dynamic variables will be like this
for($i=0;$i<=3;$i++){
$name = 'srange'.$i;
$$name = $i;
}
This may be helpful to you:
$srange0;
$srange1;
$srange2;
for($i=0;$i<=3;$i++) {
$range = "srange".$i;
$$range = $i;
}
echo $srange2."<br />";
exit;

Categories