How to declare looping (for) values as a variable
I wrote a looping function as below :
for($x=0; $x<5; $x++){
echo "'$x'";
if($x!=4){
echo ", ";
}
}
That will give result
'0', '1', '2', '3', '4'
How can i declare the result as a variable so that i could call and use it. For example, the result above is declared as $values. so that, i only need to call $values to get the '0', '1', '2', '3', '4'. Hope that's开发者_如何学JAVA clear enough to deliver my problem.
You're looking for the range
function:
$upToFour = range(0, 4);
Alternatively, you can construct the array in a loop:
$upToFour = array();
for ($i = 0;$i < 5;$i++) {
$upToFour[] = $i; // Equivalently: array_push($upToFour, $i);
}
If you want to construct the resulting string, use implode
:
$upToFourString = implode(',', $upToFour);
, or, if you need the quotes:
$upToFourString = implode(',',
array_map(
function($num) {return "'" . $num . "'";},
$upToFour));
, or, equivalently,
$upToFourString = '';
for($x=0; $x<5; $x++){
$upToFourString .= "'$x'";
if($x!=4){
$upToFourString .= ", ";
}
}
this will do it with least change in your code
<?php
ob_start();
for($x=0; $x<5; $x++){
echo "'$x'";
if($x!=4){
echo ", ";
}
}
$values = ob_get_contents();
ob_end_clean();
echo $values;
?>
$result = array();
for ($x=0; $x<5; $x++)
$result[] = $x;
Quite simply:
$a = array();
for($x=0; $x<5; $x++){
array_push($a, $x);
}
精彩评论