phparrayscompare

Determine if values in a flat array are greater than the corresponding value in another flat array


I want to check if every value in $stock is higher than the value with the same index in $request.

$stock = array("7", "5", "3");
$request = array("3", "6", "3");

In this case, the second $request value is higher than stock value (6 vs 5) -- so there is insufficient stock.

How can I check if there are any values in $request that are higher than the respective value in $stock?

Example of my database


Solution

  • Simply loop through the arrays and compare the indexes in the respective arrays. Since it's a fixed length, always, there isn't need for any complex checks or handlings. This assumes that the keys are assigned by PHP, so they all start at 0 and always increase by 1.

    $stock   = array("7", "5", "3");
    $request = array("3", "6", "3");
    var_dump(validate_order($stock, $request)); // false
    
    $stock   = array("7", "5", "3");
    $request = array("3", "4", "3");
    var_dump(validate_order($stock, $request)); // true
    
    function validate_order($stock, $request) {
        foreach ($stock as $key=>$value) // Fixed length, loop through
            if ($value < $request[$key])
                return false; // Return false only if the stock is less than the request
        return true; // If all indexes are higher in stock than request, return true
    }
    

    Since this function returns a boolean, true/false, simply use that in an if-statement, like this

    if (validate_order($stock, $request)) {
        /* Put your code here */
        /* The order is valid */
    } else {
        /* Order is not valid */
    }
    

    Live demo