Snippet Compatibility with PHP 8

I’ve got this small snippet that displays (in this case) pagination when at a certain level below a parent. I’ve just updated the site to MODX 2.8.8 and PHP 8.3 and it’s throwing an error…

Snippet…

<?php
$id = $modx->resource->get('id');
$levelcount = count($modx->getParentIds($id));
$output .= $levelcount;
return $output;

Error…

PHP warning: Undefined variable $output

…it’s still working but does it need adjustment to remove the error? Thank you.

You are using the concatenating assignment operator → .=
This line is the same as $output = $output . $levelcount;. So you concatenate $levelcount to a variable $output that is never initialized and unknown to the compiler.

1 Like

Well, thank you Harry - all way above my designer head. Any fix, gratefully received. :grinning:

1 Like

Just declare and initialize the variable $output before you use it:

<?php
$id = $modx->resource->get('id');
$levelcount = count($modx->getParentIds($id));
$output = ''; // <--- added line
$output .= $levelcount;
return $output;

In the case of this exact snippet, I see no need to use $output at all.
You could return $levelcount directly

<?php
$id = $modx->resource->get('id');
$levelcount = count($modx->getParentIds($id));
return $levelcount;

or if you want the return value to be a string, cast it to a string before returning it:

<?php
$id = $modx->resource->get('id');
$levelcount = count($modx->getParentIds($id));
return (string) $levelcount;
1 Like

As ever Harry - I’m most grateful - you’re a star.

This topic was automatically closed 2 days after discussion ended and a solution was marked. New replies are no longer allowed. You can open a new topic by clicking the link icon below the original post or solution and selecting “+ New Topic”.