Home > Net >  PHP: Keeps return as true
PHP: Keeps return as true

Time:03-17

I cant figure out what i´m doing wrong. I keeps returning "På lager" in the if statement. But Shop 3, should return "Ikke på lager" in the foreach loop, where it calls the function.

<?php

$shopsArray = array(
    "Shop1" => array (
        "price" => 5,
        "extUrl" => "https://tv2.dk/",
        "logo" => "",
        "stock" => "in stock",
        "ean" => "5707400342642",
        "shopName" => "Shop2",
    ),
    "Shop2" => array (
        "price" => 99,
        "extUrl" => "https://cnn.com/",
        "logo" => "https://eb.dk/",
        "stock" => "in stock",
        "ean" => "51010101010",
        "shopName" => "Shop2.dk",
    ),
    "Shop3" => array (
        "price" => 50000000,
        "extUrl" => "https://v2.dk/",
        "logo" => "https://eb.dk/",
        "stock" => "out of stock",
        "ean" => "5707406556565655",
        "shopName" => "Shop3",
    )

    );

foreach($shopsArray as $abc){
    echo CheckStock();
}
function checkStock(){
    global $shopsArray;

    foreach ($shopsArray as $stockMgmt) {

        if ($stockMgmt["stock"] == "in stock"){
            return "På lager";
        } else {
            return "Ikke på lager";
        }
    }
}

CodePudding user response:

You return from your checkStock() function as soon as $stockMgmt["stock"] == "in stock", and you do that three times. Try this code instead:

<?php

$shops = [
    "Shop1" => [
        "price" => 5,
        "stock" => "in stock",
        "ean" => "5707400342642",
        "shopName" => "Shop2",
    ],
    "Shop2" => [
        "price" => 99,
        "stock" => "in stock",
        "ean" => "51010101010",
        "shopName" => "Shop2.dk",
    ],
    "Shop3" => [
        "price" => 50000000,
        "stock" => "out of stock",
        "ean" => "5707406556565655",
        "shopName" => "Shop3",
    ]
];

function checkStock($stockManagement)
{
    return ($stockManagement["stock"] == "in stock") ? "På lager" : "Ikke på lager";
}

foreach ($shops as $shop => $stockManagement) {
   echo $shop . ' = ' . CheckStock($stockManagement) . '<br>';
}

The function now uses the stock management array as an argument. In the function I use the Ternary Operator.

We only use one loop to walk through the main array of shops.

Note how I don't abbreviate unnecessarily. Variable names should clarify the meaning of the value, but not the type. So, not $shopsArray but just $shops or $shopsStock.

Now tested, thanks to medilies: PHP fiddle

  • Related