How i can get the numbers on the left and the right of the given element?

284 views Asked by At

Given a string:

$pages = "1,2,3,4,5,6";

Create a function that gets the numbers on the left and the right of the given element. I expect this ouputs:

pagination(1); // array('prev' => null, 'next' => 2);
pagination(2); // array('prev' => 1, 'next' => 3);
pagination(6); // array('prev' => 5, 'next' => null);

I don't want to use explode() i want to use only only use string manipulation functions. This it's was i tried but is 8 apear ... i need to see, the 5 between ','

<?php
$number = "5";
$pages = "1,2,3,4,5,6";
$x = strpos($pages, $number);

echo $x;

?>
3

There are 3 answers

4
Tool On BEST ANSWER

Haven't tested it, but I think this could give you an idea.

This doesnt work for numbers >= 10.

function get_near_elems($number = 5)
 {
        $pages = "1,2,3,4,5,6";
        $x = strpos($pages, $number);

        if($x == 0)
          return array('prev' => null, 'next' => $pages[$x]);
        else if($x == (strlen($pages) - 1))
          return array('prev' => $pages[$x - 2], 'next' => null);
        else
             return array('prev' => $pages[$x - 2], 'next' => $pages[$x + 2]);
}

Since this looks like homework, I suggest you take something you see here and modify it.

0
Bas Slats On

I would use a function similar to the following one, just need to make sure the pages variable is accessible in the function.

function getPreviousAndNext($number)
{
    $location = strpos($pages, number);

    $previous = ($number > 0 ? substr($pages, ($location - strlen($number - 1)), strlen($number - 1) + 1) : null);
    $next = ($number == strlen($pages) - 1 ? null : substr($pages, ($location + strlen($number + 1)) + 1, strlen($number + 1));

    return [
        "previous" => $first,
        "next" => $last
    ]
}
0
daxeh On

explode() would be helpful but given the constraints:

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

gives the position of the index in string, try removing ',' by using str_replace()

// removes ',' from string
str_replace(',', '', $pages); 

which results in "123456" then strpos($pages, $number) will gives you the index of the index position 4. Given validations ( bounds check ) ie. > 0 and < strlen(..), you can get the previous and next with -1 and +1.

Hope this helps.