1

If I had an array like this...

array('1','2','3','4','10')

... how could I remove elements before the element whose value I supply.

For example:

If I supplied 1 then array = (1,2,3,4,10)

If it were 2 then array = (2,3,4,10) //Remove the numbers before 2

If it were 3 then array = (3,4,10) //Remove the numbers before 3

If it were 4 then array = (4,10) //Remove the numbers before 4

If it were 10 then array = (10) //Remove all before the 10

I'm currently thinking of doing with using if else. But is there a way to do this using some kind of php array function itself.

2
  • If an enumerative array, use array_search() to find the element key, and then use array_splice() Commented Jan 24, 2014 at 8:05
  • @MarkBaker My array is just like the one in my question. $array = array("1","2","3","4","10") Commented Jan 24, 2014 at 8:09

4 Answers 4

1

Make use of array_search and array_slice

<?php
$arr=array_slice($arr, array_search('4',array('1','2','3','4','10')));
print_r($arr);

OUTPUT :

Array
(
    [0] => 4
    [1] => 10
)

Demo

Sign up to request clarification or add additional context in comments.

Comments

1

Maybe this would help:

 $myArray = array('1','2','3','4','10');
 $x=3;
 $myArray = array_splice($myArray, array_search($x, $myArray), count($myArray));

Comments

1
$myArray = array('1','2','3','4','10');
$value = 3;

$key = array_search($value, $myArray);
$myNewArray = array_splice($myArray, 0, $key);

3 Comments

You've got several things mixed up in your answer. Eg: $myArray and $value in the 3rd line and the offset in the fourth line.
And your final output are the number before the supplied number, while it should have been the ones after it.
Hmmmm, I execute it with $value=3 and I get a $myArray value of [3,4,10] and $myNewArray value of [1,2] which I thought was your expectation... you can discard $myNewArray if you want and simply use array_splice($myArray, 0, $key); to update $myArray
0
$array = array_filter($array, function($item) use ($filterItem) {
    return $item !== $filterItem;
});

Will filter out every item equal to $filterItem. array_filter on php.net

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.