user3078404
user3078404

Reputation: 1

how to slice an array with specific value

I have an array, i would like to slice the array when "Onsite" is found. I have tried slice function didn't able to achive with specific word. Thanks for the help in advance !

Output :

 Array
(
    [0] => 1968
    [1] =>  ARNAVUTKÖY/İSTANBUL ŞUBESİ
    [2] => 212 597-0461
    [3] => 212 597-0075
    [4] => Arnavutköy
    [5] => İSTANBUL
    [6] => Arnavutköy Merkez Mah. Necip Fazıl Cd. No: 16 / 1 34275 Arnavutköy İstanbul 
    [7] => 41.18437
    [8] => 28.74354
    [9] => Onsite
    [10] => 1008
    [11] =>  HADIMKÖY/İSTANBUL ŞUBESİ
    [12] => 212 771-2177
    [13] => 212 771-2340
    [14] => Arnavutköy
    [15] => İSTANBUL
    [16] => Hadımköy Mah. Ayasofya Cd. No: 36 A / 1 34555 Arnavutköy İstanbul 
    [17] => 41.15646
    [18] => 28.61973
    [19] => Onsite
)

Expected output:

 Array
(
    [0] => 1968
    [1] =>  ARNAVUTKÖY/İSTANBUL ŞUBESİ
    [2] => 212 597-0461
    [3] => 212 597-0075
    [4] => Arnavutköy
    [5] => İSTANBUL
    [6] => Arnavutköy Merkez Mah. Necip Fazıl Cd. No: 16 / 1 34275 Arnavutköy İstanbul 
    [7] => 41.18437
    [8] => 28.74354
)

Array
    (
        [0] => 1008
        [1] =>  HADIMKÖY/İSTANBUL ŞUBESİ
        [2] => 212 771-2177
        [3] => 212 771-2340
        [4] => Arnavutköy
        [5] => İSTANBUL
        [6] => Hadımköy Mah. Ayasofya Cd. No: 36 A / 1 34555 Arnavutköy İstanbul 
        [7] => 41.15646
        [8] => 28.61973
)

Upvotes: 0

Views: 670

Answers (2)

Philipp
Philipp

Reputation: 15629

You could use array_search to find the index - if the value doesn't exists, this function returns false. Doing this would result in something like this:

$index = array_search('Onsite', $a);
if ($index !== false) {
    $first = array_slice($a, 0, $index);
    $second = array_slice($a, $index + 1);
}

Upvotes: 0

Manwal
Manwal

Reputation: 23816

Consider following:

$arr = array(1,2,3);
$slice_value = 2;
sliceByValue($arr, $slice_value);
function sliceByValue($arr, $val) {
    $index = array_search($val, $arr);
    $first = array_slice($arr, 0, $index);
    $second = array_slice($arr, $index+1, count($arr)-1);
    print_r($first);
    print_r($second);
}

Put your array and value and check you are getting expected output or not.

Upvotes: 1

Related Questions