Home > database >  Array being populated when meeting certain condition
Array being populated when meeting certain condition

Time:03-10

I'm currently trying to have an associative array take values if another array is "full". There are two asso arrays which represent parking lots (one for small cars and the other for larger cars) the small cars can park in the larger spots if theirs are all occupied. I got this to work but i'm stuck on one bit of logic which i don't seem to get.

The small array exists of 10 spots and the large one 14. The bit that causes me trouble is ( $_SESSION['parkingLarge']["spot1"] === 0 && $_SESSION['parkingSmall']["spot10"] === 1) I understand that this is to be expected because when it breaks out of the first foreach loop it will fullfill the condition in the next statement and add the last 1 to spot10 in the first array and automatically it will also add it in the 1st spot of the larger array.

Is there a way i could stop this behavior , or code this in a better way ?

Arrays are :

$parkingSmall = array(
    "spot1" => 1, "spot2" => 1, "spot3" => 1, "spot4" => 1, "spot5" => 1,
    "spot6" => 1, "spot7" => 1, "spot8" => 1, "spot9" => 0, "spot10" => 0
);

$parkingLarge = array(
    "spot1" => 0, "spot2" => 0, "spot3" => 0, "spot4" => 0, "spot5" => 0,
    "spot6" => 0, "spot7" => 0, "spot8" => 0, "spot9" => 0, "spot10" => 0,
    "spot11" => 0, "spot12" => 0, "spot13" => 0, "spot14" => 0
);

$_SESSION['parkingSmall'] = $parkingSmall;
$_SESSION['parkingLarge'] = $parkingLarge;

code

if ($_POST["size"] == 'small') {

    foreach ($_SESSION['parkingSmall'] as $key => $value) {
        if ($value === 0) {
            $_SESSION['parkingSmall'][$key] = 1;
            echo "Car parked";
            break;
        }
    }
    if ( $_SESSION['parkingLarge']["spot1"] === 0 && $_SESSION['parkingSmall']["spot10"] === 1) {
        foreach ($_SESSION['parkingLarge'] as $key => $value) {
            if ($value === 0) {
                $_SESSION['parkingLarge'][$key] = 1;
                echo "Small car parked in large spot";
                break;
            }
        }
    }
    if ($_SESSION['parkingLarge']["spot14"] === 1) {
        echo "No more spaces available in both parkings";
        return false;
    }
}

Any help on this is more than welcome !!!

CodePudding user response:

You could use array_search for this case, e.g:

$type = 'small';
$key = array_search(0, $_SESSION['parkingSmall']) ?: null;
if (!$key) {
    $type = 'large';
    $key = array_search(0, $_SESSION['parkingLarge']) ?: null;
}
var_dump($type, $key);
    
  • Related