0

I have a PHP array like below:

  Array
    (
        [0] => 16
        [1] => 17
        [2] => 18
        [3] => 23
        [4] => 7
        [5] => 6
        [6] => 14
        [7] => 22
    )

I need two split this array in to two arrays by 23 value it will be like below:

 Array
    (
        [0] => 16
        [1] => 17
        [2] => 18
    )

 Array(
        [0] => 23
        [1] => 7
        [2] => 6
        [3] => 14
        [4] => 22
    )

Can any one know how to do this with PHP.

1 Answer 1

7

The 23 in the code below is hardcoded, and the original array will be split only if the 23 value found in the source array:

$arr = array(16, 17, 18, 23, 7, 6, 14, 22);
$split_by = array_search(23, $arr);

if ($split_by) {
    $first = array_slice($arr, 0, $split_by);
    $second = array_slice($arr, $split_by);

    var_dump($first, $second);
}

http://ideone.com/BPn7t

or

$arr = array(16, 17, 18, 23, 7, 6, 14, 22);
$split_by = array_search(23, $arr);

if ($split_by) {
    $first = array_slice($arr, 0, $split_by + 1);
    $second = array_slice($arr, $split_by + 1);

    var_dump($first, $second);
}

if you need to left the found value in the first array

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

1 Comment

@smith bandara: added second example

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.