6

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.

1
  • have you looked at array_splice? ie: array_splice( $days,0, 4 ); Commented Nov 11, 2015 at 9:22

3 Answers 3

7

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
)
Sign up to request clarification or add additional context in comments.

Comments

3

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);

Comments

0

Your array

$days = array
(
     1=>"Sunday",
     2=>"Monday",
     3=>"Tuesday",
     4=>"Wednesday",
     5=>"Thursday",
     6=>"Friday",
     7=>"Saturday"
);

Loop to remove all element before a specified index.

# Number to stop the unset.
$split_number =4;
# Loop through array

for($a=0;$a<sizeof($days);$a++)
{
    if($a < $split_number)
        # Unset element if condition is true
        unset($days[$a]);
}

print_r($days);

Result

Array
(
    [4] => Wednesday
    [5] => Thursday
    [6] => Friday
    [7] => Saturday
)

If you wish the indexes to start from 0 again, you can use the array_values

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.