Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Delete all array elements before a specific one

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.

like image 444
coder Avatar asked Nov 11 '15 09:11

coder


2 Answers

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
)
like image 64
syck Avatar answered Oct 28 '22 14:10

syck


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);
like image 3
Marcin Avatar answered Oct 28 '22 16:10

Marcin