0

I have a function that first looks for premium brands to add to a string. If there is not enough premium brands, it continues and ads non-premium brands (max 4 brands).

I'm able to echo the string inside the function and it shows 4 brands, but I'm not able to return the string. Why is that?

$bnames = addBrandNameToTitle($model);
echo $bnames; // This is empty

function addBrandNameToTitle($model, $brandNames = array(), $ispremium = true){
    if($ispremium):
        foreach ($model->brands as $brand):
            if ($brand->isPremium() && count($brandNames)  < 4):
                array_push($brandNames, $brand->name);
            endif;

            if(count($brandNames)  >= 4){
                return implode(',', $brandNames);
            }
        endforeach;
        // If not enough premium, add non-premium brands
        addBrandNameToTitle($model, $brandNames, false);
    else:
        foreach ($model->brands as $brand):
            if (!$brand->isPremium() && count($brandNames) < 4):
                array_push($brandNames, $brand->name);
            endif;
        endforeach;
        $bnames = implode(',', $brandNames);
        echo $bnames; // <-- This lists 4 brands
        return $bnames; // <-- But this is not returning the string. Why?
    endif;
}
0

1 Answer 1

3

In this section of code, you forgot to return the value

// If not enough premium, add non-premium brands
return addBrandNameToTitle($model, $brandNames, false);  // Add a return
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. That was it. I've never had to use return before. Can you explain why I need that and simply not just calling the function recursively with parameters?
The first time you call the function, $isPremium is true. This means that the first part of the if statement is executed. The only return statement is in the else part, which doesn't get executed. Because there is no explicit return, the function returns nothing. This is regardless of any recursion or anything else that might be happening.

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.