Fix Undefined Variable in PHP 8
PHP 8 is a lot stricter than previous versions of it. In updating I was receiving a lot of “undefined variable” warnings with code that previously worked fine.
This is how you can fix it.
In your code snippet below, we want to define and concatenate three separate variables, namely $output1, $output2, and $output3, to create a final output variable $output. To do this correctly, we can define and initialize these variables before using them in our code.
$output1 = ”;
$output2 = ”;
$output3 = ”;
/* Loop through categories */
$output1 .= ‘<div class="cf-category-holder"><div class="cf-category-title">Sort by Category</div>’;
foreach($categories as $category) :
$output2 .= ‘<div class="cf-category-list"><a class="cf-category-list-item" href="#!" data-slug="’. $category->slug .’">
‘.$category->name.’
</a><span class="cf-category-count">’.$category->count . ‘</span></div>’;
endforeach;
$output3 .= ‘<div class="cf-category-list-last"><a class="cf-category-list-item active" href="#!" data-slug="’.$cat_in_use.’">View All Posts</a></div></div>’;
/* Concatenate the output variables */
$output = $output1 . $output2 . $output3;
/* Return the final output */
return $output;
[/php]
By initializing the variables $output1, $output2, and $output3 with empty strings before using them, you can concatenate the HTML content within your loop and afterward to create the final output as desired.