1

I have following list:

$radiusList = [
    '2'   => '2km',
    '5'   => '5km',
    '10'  => '10km',
    '25'  => '25km',
    '50'  => '50km',
    '100' => '100km',
    '200' => '200km',
    '500' => '500km',
];

I am getting currently selected radius via POST:

$radius = $_POST['radius'] ? $_POST['radius'] : 2;

And I have to go to the next radius if the result is empty. This is my do/while loop:

$clinics     = [];
$radiusCount =  count($radiusList);
$i = 0;

do {

    $radius  = $radiusList[$radius];

    $clinics = $this->clinicQuery($conditionsQuery, $lat, $lng, $radius);
    $i++;

} while  (!empty($clinics) && $i <= $radiusCount);

How can I set current radius (from the radius list) and if the result from the clinicQuery is empty go to the next element in the array and take key value?

2
  • 1
    This would be a bit easier if you would not use an associative array to begin with (which seems rather superfluous, since all your values are just the key suffixed with km anyway) … Make that $radiusList = [2, 5, 10, …] instead, and then simply find the index of your POSTed value in that, and use it as starting value for $i, so that inside your loop you can use that index to access the values. Commented Jun 25, 2018 at 13:40
  • This is quite good idea. I guess I got code blindness I tried to go with more complicated way. That a lot for the idea :) Commented Jun 25, 2018 at 14:00

2 Answers 2

1

You can rewrite your loop with foreach + break:

$radius = $_POST['radius'] ? $_POST['radius'] : 2;

foreach ($radiusList as $index => $radius_str) {
    // check that current index value is greater or equals `$radius`
    // it will skip values that are less than `$radius`
    if ($index >= $radius) {
        // find clinics
        $clinics = $this->clinicQuery($conditionsQuery, $lat, $lng, $index);
        // if clinics found - break the loop
        if (!empty($clinics)) {
            break;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I would do this in a foreach instead.

$clinics = [];
$radiusList = array_filter($radiusList, function($index) use ($radius) {
    return $index >= $radius;
}, ARRAY_FILTER_USE_KEY);
ksort($radiusList); // if you need to make sure the list is ordered
foreach ($radiusList as $distance => $distanceLabel) {
    $clinics = $this->clinicQuery($conditionsQuery, $lat, $lng, $radius);
    if (!empty($clinics)) {
        break;
    }
}

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.