Jakub Adamec
Jakub Adamec

Reputation: 1124

Is there a function to get N nearest numbers of the specific number?

Is there a built-in function to get nearest N numbers of the specific number using PHP, please? I mean, we have for example number 5. Now, I need to get an array like this [3, 4, 5, 6, 7].

So, I'm looking for some function nearestNumbers(5, 2), where 5 - specific number, and 2 - amount of numbers up/down to specific number, which does [3, 4, 5, 6, 7]. Thanks!


In reality, when using Laravel pagination with custom $elements.. this looks really strange:

[
$paginator->currentPage()-2,
$paginator->currentPage()-1,
$paginator->currentPage(),
$paginator->currentPage()+1,
$paginator->currentPage()+2
]

Upvotes: 0

Views: 53

Answers (1)

phparkle
phparkle

Reputation: 86

The best you can do with a built-in function is probably range:

range( $paginator->currentPage()-2, $paginator->currentPage()+2 )

You could write a helper function like this:

function nearestNumbers( $x, $d ) {
    return range( $x - $d, $x + $d );
}

You could use min and max to limit the range:

function nearestNumbers( $x, $d, $lim ) {
    return range( max( $x - $d, 1 ), min( $x + $d, $lim ) );
}

Documentation: https://www.php.net/manual/en/function.range.php

Upvotes: 2

Related Questions