How to get the previous value from incrementing variable in for loop?
In My last post I asked : How to create dynamic incrementing variable using "for" loop开发者_JS百科 in php? like wise: $track_1,$track_2,$track_3,$track_4..... so on....
whose answer I selected as
for($i = 0; $i < 10; $i++) {
$name = "track_$i";
$$name = 'hello';
}
and
for($i = 0; $i < 10; $i++) {
${'track_' . $i} = 'val'
}
Now, What If I need the Value of variable previous than the current variable?
for($i = 0; $i < 10; $i++) {
${'track_' . $i} = 'val'
if($i != 0){
$prev_val = ${'track_' . ($i - 1)}
}
}
But it's much better to use arrays for this, which are meant for this application.
$tracks = array();
for($i = 0; $i < 10; $i++){
$tracks[$i] = 'val';
if($i != 0){
$prev_val = $tracks[$i-1];
}
}
I guess the simples way would be to use two variables.
$name2 = "track_0";
for($i = 1; $i < 10; $i++) {
$name1 = $name2;
$name2 = "track_$i";
$$name1 = 'hello_previous';
$$name2 = 'hello_this';
}
Or if you explicitly use i = [0...10] to generate a variable name, you could simply write $name2 = "track_". $i; $name1 = "track_" . ($i - 1);
I know the others are saying just subtract by 1, but what if your list goes 1, 2, 4, 5, 8, 9? The previous of 8 is not 7, but 5, this following method (with a bit of modification to work as you require) will provide a way of getting the true previous value, and not a guessed one.
for($i = 0; $i < 10; $i++) {
${'track_' . $i} = 'val'
if(!empty($last_val))
// do what you want here
// set a var to store the last value
$last_val=$i;
}
if ($i != 0)
{
$prev = ${'track_' . ($i-1)} ;
}
?
${'track_' . ($i-1)};
won't suffice?
精彩评论