iSUSO
iSUSO

Reputation: 3

How can I store for loop in a variable?

How can I store this in a $_var variable ?

$s_number = 5;
$spn      = '6';

echo "'Landscapes':[";
for ($i = 1; $i <= $s_number; $i++)
{
    echo "'".$spn."/"."content"."/".$i.".png"."'".", ";
}
echo "]";

Upvotes: 0

Views: 95

Answers (3)

Kash Singh
Kash Singh

Reputation: 56

You could also try putting the for loop in a function passing your variables and then return the values to a new variable. That's like saving a loop in a variable.

Upvotes: 0

Rikesh
Rikesh

Reputation: 26431

Question is bit vague though it seems probably you are looking for this,

 $string = "'Landscapes':[";
 for ($i = 1; $i <= $s_number; $i++) {
     $string .= "'".$spn."/"."content"."/".$i.".png"."'".", ";
 } 
 $string .= "]";
 echo $string;

Upvotes: 1

Giacomo1968
Giacomo1968

Reputation: 26066

Other suggestions that use strings are fine, but I prefer to create arrays for tasks like this:

$s_number = 5;
$spn = '6';
$landscapes_array = array();
for ($i = 1; $i <= $s_number; $i++) {
    $landscapes_array[] = "'".$spn."/"."content"."/".$i.".png"."'".", ";
}
$landscapes = "'Landscapes':[" . implode('', $landscapes_array) . "]";

Upvotes: 0

Related Questions