1

I want to create my custom array slicing after certain indexes on each function call, I've defined the upperlimit and lower limit of the array indexes such that from starting limit to ending limit, I want to slice my array on each function call. I'm working in PHP and trying to get next array slices on each calling.

Im explaining it more by showing up my function,

function mycustomslicing($startingLimit = 0, $endingLimit = 10){

        if ($startingLimit > 0)
            $startingLimit = $startingLimit*$endingLimit;

 for ($i=0; $i < $endingLimit ; $i++) { 
                $arr2[]  = $arr1[$startingLimit+$i];
            }
}

calling my function:

mycustomslicing(0, 10)
mycustomslicing(11, 20)
mycustomslicing(21,30)

My results:

i'm getting first iteration fine but onwards, it shows me index offsets warning.

My Desired results:

on mycustomslicing(0, 10) call:

$arr2 will be, all values from $arr1 from index 0 to 10.

on mycustomslicing(11, 20) call:

$arr2 will be, all values from $arr1 from index 11 to 20.

on mycustomslicing(21, 30) call:

$arr2 will be, all values from $arr1 from index 21 to 30.

1 Answer 1

3

Just use the built-in array_slice function. It takes a start and length, so you can subtract your starting limit from ending limit. You also need to pass the array as an argument to the function.

function mycustomslicing($arr1, $start, $end) {
    return array_slice($arr1, $start, $end - $start);
}

You use this as:

$arr2 = mycustomslicing($arr1, 0, 10);
$arr2 = mycustomslicing($arr1, 11, 20);

and so on.

You're getting an error because you're multiplying the start by the end, which is making the starting limit much too high.

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

2 Comments

it also gives me array(0) { } on second index.
please give an exmaple how to use this in my case.

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.