1

I have an array like this

$baseArray = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 );

So i want to make two arrays of range

$arrayOne = from index 5 - 10
$arrayTwo = from index 15 - 20

How can I split the $baseArray to make arrays like that in php ?

4
  • Did you read any of the php.net documentation ? Commented Dec 7, 2014 at 9:03
  • @Rizier123 I tried array_chunk function and array_slice but no result. Commented Dec 7, 2014 at 9:04
  • @Mihaiiorga I read but the functions I used did not worked Commented Dec 7, 2014 at 9:04
  • There is native function array_alice Commented Dec 7, 2014 at 9:08

3 Answers 3

2

There is function array_slice

$baseArray = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 );
$arrayOne = array_slice($baseArray, 5, 10);
$arrayTwo = array_slice($baseArray, 15, 20);
Sign up to request clarification or add additional context in comments.

Comments

0

This should work for you:

(Only works if you have an index with numbers start's with 0)

$baseArray = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 );
$arrayOne = array();
$arrayTwo = array();

foreach($baseArray as $k => $v) {

    if($k >= 5 && $k <= 10)
        $arrayOne[] = $v;
    elseif($k >= 15 && $k <= 20)
        $arrayTwo[] = $v;

}

print_r($arrayOne);
print_r($arrayTwo);

Output:

arrayOne:

Array
(
    [0] => 6
    [1] => 7
    [2] => 8
    [3] => 9
    [4] => 10
    [5] => 11
)

arrayTwo:

Array
(
    [0] => 16
    [1] => 17
    [2] => 18
    [3] => 19
    [4] => 20
)

Comments

0

Can try using for() & array_slice(). Example:

$baseArray = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 );
$newAr = array();
for($i = 5; $i < count($baseArray); $i += 10){
    $newAr[] = array_slice($baseArray, $i, 5);
}
print '<pre>';
print_r($newAr);
print '</pre>';

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.