Hi I've got the following array:
$days = array(
1=>"Sunday",
2=>"Monday",
3=>"Tuesday",
4=>"Wednesday",
5=>"Thursday",
6=>"Friday",
7=>"Saturday"
);
Now I want to make a loop that automatically removes all objects before number 4.
I tried this:
$startIndex = 4;
for($i = 1; $days < $startIndex; $i++)
{
unset($days[$i]);
}
But it does not work.
A shorter solution may be given using array_slice():
$days = array(
1=>"Sunday",
2=>"Monday",
3=>"Tuesday",
4=>"Wednesday",
5=>"Thursday",
6=>"Friday",
7=>"Saturday"
);
$startIndex = 4;
$days = array_slice($days, $startIndex-1, NULL, TRUE);
print_r($days);
returns
Array
(
[4] => Wednesday
[5] => Thursday
[6] => Friday
[7] => Saturday
)
Change $days to $i as $i is your index value.
$days = array(
1=>"Sunday",
2=>"Monday",
3=>"Tuesday",
4=>"Wednesday",
5=>"Thursday",
6=>"Friday",
7=>"Saturday"
);
$startIndex = 4;
for($i = 1; $i < $startIndex; $i++)
{
unset($days[$i]);
}
print_r($days);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With