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;
}
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments