Slice an array in php

I have an array

print_r($myarray);

Array ( [0] => text one ) Array ( [0] => text two ) Array ( [0] => text three ) ...  

When i use slice

print_r(array_slice($myarray,1,2));

Array ( ) Array ( ) Array ( ) Array ( ) ......

I get an empty array, how can i slice this array in half?

Thanks

1 answer

  • answered 2018-03-11 13:47 arkascha

    You actually have an array that contains arrays which probably might be what is causing the issue for you. Though I do not see how you get the result you posted... It mighty be that you actually apply the slice function to each element of the output array. Then certainly you will get an empty array for each iteration. As to be expected, since each element you iterate over contains only a single element. So slicing from position 1 will result in an empty array each time...

    Consider this simple example using a plain array:

    <?php
    $input = ["one", "two", "three", "four", "five", "six"];
    $output = array_slice($input, 1, 2);
    print_r($output);
    

    The output is:

    Array
    (
        [0] => two
        [1] => three
    )
    

    So php's array_slice() function works just as expected...


    Same with an array of arrays as you suggest in your post:

    <?php
    $input = [["one"], ["two"], ["three"], ["four"], ["five"], ["six"]];
    $output = array_slice($input, 1, 2);
    print_r($output);
    

    The output of that is, as expected:

    Array
    (
        [0] => Array
            (
                [0] => two
            )
    
        [1] => Array
            (
                [0] => three
            )
    
    )
    

    Also considering your second comment below, that you have some words in a single string (which mighty be what you describe) I get a meaningful result myself:

    <?php
    $input = explode(' ', "one two three four five six");
    $output = array_slice($input, 1, 2);
    print_r($output);
    

    The output, as expected, is:

    Array
    (
        [0] => two
        [1] => three
    )