I’m definitely sinking here - not even treading water.
I’m writing a plug-in that, instead of doing a simple search/replace of provided text, will replace $something with a $begin(ing), an incrementing counter, and an $end(ing). To do this I’m using preg_replace_callback();
It is actually working, but for every loop I’m getting a PHP notice to the tune of:
Notice: Undefined index:
in /path/to/my/plugins/pi.incrementeer.php on line 33
Line 33 is:
$output .= "$begin$counter$end" . $matches[$match];
And the plug-in in it’s entirety:
class Incrementeer {
var $return_data = "";
var $counter = 1;
function Incrementeer() {
global $TMPL;
$replace = $TMPL->fetch_param('replace');
$this->return_data = preg_replace_callback("/$replace/", array($this, 'myCallback'), $TMPL->tagdata);
}
function myCallback($matches) {
global $TMPL;
$begin = $TMPL->fetch_param('begin');
$end = $TMPL->fetch_param('end');
$output = '';
foreach($matches as $match) {
$output .= "$begin$this->counter$end" . $matches[$match];
$this->counter++;
}
return $output;
}
blah blah usage function
}
Can anyone shed some light here? I’m ok with PHP but am a (relative) newb when it comes to OO programming (self-taught in all the wrong ways). I could cheat and turn off error reporting for the duration of the script, but I don’t want to cheat…
Thank you, thank you, thank you!
What happened is that inside your foreach loop, you were using the “matches” variable. Inside that foreach loop, since you were doing matches as match…. matches is no longer defined INSIDE that loop.
You could have written it like thus:
foreach($matches as $match) {
$output .= "$begin$this->counter$end" . $match;
$this->counter++;
}
The $match variable IS the contents of that array.
I hope that helps! The concept of a foreach loop is a tough one some time.
Technically, $matches is still defined; the key however, is not. It’s a difference of:
foreach ($arr as $val)
{
echo $val;
}
vs.
foreach ($arr as $key => $val)
{
echo $arr[$key];
}
Unless you use $key => $val pairs in the foreach, the variable available in each loop will be the value itself, not the array’s keys.
Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.