2

It is necessary to remove part of the array. Here is an example of an array:

Array ( [0] => one [1] => two [2] => three [3] => four [4] => five )

The variable can be based on one of the following values ​​in the array. Suggests there is 'three'. Need to take one, two and everything else removed.

Is there any standard methods, or a good solution that would not need to use a loop?

3 Answers 3

8

You can use array_splice for that

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")
Sign up to request clarification or add additional context in comments.

4 Comments

for the question you also need to array_search() to find the offset uk.php.net/manual/en/function.array-search.php and omit length
@Grim I'm sorry, I do that sometimes :-)
What do you think about this version of the solution - askdev.ru/a/19557 ?
$=array_search will always be true even if not found. $i however will be false. look at my answer.
4

If you don't want to use a loop, you could use array_splice.

$input = array("red", "green", "blue", "yellow");
array_splice($input, $varaible, -1);
// $input is now array("red", "yellow")

Comments

4

This will use @JeroenMoons array_splice but will do the array_search I suggested too

function reduce_my_array($array, $value)
{
    // look for location of $value in $array
    $offset=array_search($value, $array);

    // if not found return original
    if($offset===false) return $array;

    // remove from the found offset to the end of the array
    return array_splice($array, $offset+1);     
}

Note:
array_search returns the INDEX which can be 0
array_splice uses number of entries as the offset
so for your example with numerical indexes 0 to ... you need to tell array splice index+1

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.