Mister PHP
Mister PHP

Reputation: 327

How to fill an array from some position

for example I have an array :

$array = array(25, 50, 75, 100); // I get an array of some numbers
$position = 50; // I get some value to start with
$limit = 3; // I need to fill another array with 3 next values from the starting position

and now what code I need to use to fill a new array just like this:

$new_array = array(75, 100, 25); // the start position is 50, but I need the next 3

any ideas??

Upvotes: 0

Views: 713

Answers (3)

Quasdunk
Quasdunk

Reputation: 15230

I like having functions to abstract the logic. So I would suggest to write a function which takes the array, the position to start with and the limit:

<?php
function loop_array($array,$position,$limit) {

    //find the starting position...
    $key_to_start_with = array_search($position, $array);
    $results = array();

    //if you couldn't find the position in the array - return null
    if ($key_to_start_with === false) {
        return null;
    } else {
            //else set the index to the found key and start looping the array
        $index = $key_to_start_with;
        for($i = 0; $i<$limit; $i++) {
                    //if you're at the end, start from the beginning again
            if(!isset($array[$index])) {
                $index = 0;
            }
            $results[] = $array[$index];
            $index++;
        }
    }
    return $results;
}

So now you can call the function with any value you want, e.g.:

$array = array(25, 50, 75, 100);
$position = 75;
$limit = 3;

$results = loop_array($array,$position,$limit);

if($results != null) {
    print_r($results);
} else {
    echo "The array doesn't contain '{$position}'";
}

outputs

Array
(
    [0] => 75
    [1] => 100
    [2] => 25
)

Or you could loop it with any other values:

$results = loop_array(array(1,2,3,4,5), 4, 5);

Here's a working example: http://codepad.org/lji1D84J

Upvotes: 2

Dhairya Vora
Dhairya Vora

Reputation: 1281

You can use array_search to find the position of the keyword inside your array. % arithmetic operator for going to first element after reaching end. Rest is your logic.

<?php
    $array = array(25, 50, 75, 100);
    $position = 10;
    $limit = sizeof($array)-1;

    $pos = array_search($position, $array);;

    if(!($pos === false))
    {
        for($i=0;$i<$limit;$i++)
        {
            $pos = (($pos+1)%sizeof($array));
            echo $array[$pos]."<br>";
        }
    }
    else
    {
        echo "Not Found";
    }
?>

Upvotes: 2

interskh
interskh

Reputation: 2591

You can use array_slice() and array_merge() to achieve your goal.

let's say you know the position of 50 is at 2.

then you can get a new array by -

array_slice(array_merge(array_slice($array, 2), array_slice($array, 0, 2)), 3);

Basically, you get two sub-array from the start position, concatenate together, and then remove the tailing part.

Upvotes: 1

Related Questions