Search code examples
phparraysunset

Sub-array returned by function sometimes cannot be used due to "value of type null"


The following PHP code randomly selects an oven from an array of ovens. If the selected oven does not pass any of the filters, it gets removed from the array and the function recursively executes itself until a qualified oven is found. The sub-array of the qualified oven that is found then gets returned for displaying as the featured oven.

There might be other kinds of appliances (e.g. refrigerators, blenders, dish washers, etc) which need their products to be randomly featured, too. Thus the reusable $get_featured_product function is created.

The number of array elements of each kind of appliances can increase.

$get_featured_product = function ($products) use (&$get_featured_product)
{
    $rand_key = array_rand($products);
    if ($products[$rand_key]['rating'] < 7 || $products[$rand_key]['discount'] < 30 || $products[$rand_key]['deal'] != 'On Sale')
    {
        unset($products[$rand_key]);
        $get_featured_product($products);
    }
    else
    {
        return $products[$rand_key];
    }
};

$ovens = array(
    array(
        'name' => 'Wonderful Oven',
        'rating' => 5.0,
        'discount' => 10,
        'deal' => 'Free Shipping'
    ),
    array(
        'name' => 'Greatest Oven',
        'rating' => 7.3,
        'discount' => 40,
        'deal' => 'On Sale'
    ),
    array(
        'name' => 'Fantastic Oven',
        'rating' => 4.7,
        'discount' => 60,
        'deal' => 'Clearance'
    ),
    array(
        'name' => 'Remarkable Oven',
        'rating' => 8.6,
        'discount' => 30,
        'deal' => 'On Sale'
    ),
    array(
        'name' => 'Incredible Oven',
        'rating' => 3.2,
        'discount' => 20,
        'deal' => 'Black Friday'
    ),
    array(
        'name' => 'Superb Oven',
        'rating' => 6.3,
        'discount' => 50,
        'deal' => 'Clearance'
    )
);

$featured_oven = $get_featured_product($ovens);
echo "Featured Oven: {$featured_oven['name']} (Rating: {$featured_oven['rating']}; Discount: {$featured_oven['discount']}% OFF)";

The issue I encountered is that, sometimes the code fails due to the following notices:

Notice: Trying to access array offset on value of type null in php_file_path

But the array does contain qualified ovens so the returned sub-array is supposed to work. I cannot figure out why there is/are null value(s).

Note: I previously asked a similar question. But the code was overly simplified by me and could not really reflect the issue I encountered. Sorry about that. This time, I believe the question does reflect the issue.


Solution

  • You have a condition that does not return anything:

    if (...)
    {
        unset($products[$rand_key]);
        $get_featured_product($products);
        // ^ add a return here
    }
    else
    {
        return $products[$rand_key];
    }