0

It's strange that when I run the code below in a function, it executes it, but when I run it inside a while loop it gives me this notice:

Notice: Uninitialized string offset: 4

function thing($content) {

preg_match_all("/(<h[^>]*>.*?<\/h2>\n*<p>.*?<\/p>)/", $content, $array);

$i = 1;
$limit = count($array[0]);

$array = $array[0][4];
echo $array; //outside loop

while ( $i <= $limit) {
  $array = $array[0][4];
  echo $array; inside loop
  $i++;
}
return $content;
}
add_action('the_content', 'thing', 50);

Why is this happening?

I want to access the array keys one at a time so doing this $array = $array[0][4]; is required

1 Answer 1

0

That error means you're attempting to address a string or null as if it were an array. Perhaps it's returning fewer than 5 matches, in which case $array[0][4] would be unset.

Here's your problem:

function thing($content) {

preg_match_all("/(<h[^>]*>.*?<\/h2>\n*<p>.*?<\/p>)/", $content, $array);

$i = 1;
$limit = count($array[0]);

$array = $array[0][4]; // you've overwritten $array with what used to be $array[0][4]
echo $array; //outside loop

while ( $i <= $limit) {
  $array = $array[0][4]; // now you're trying to overwrite $array again once for every time you go around the loop
  echo $array; inside loop
  $i++;
}
return $content;
}
add_action('the_content', 'thing', 50);

Let's rewrite it a bit:

function thing($content) {

preg_match_all("/(<h[^>]*>.*?<\/h2>\n*<p>.*?<\/p>)/", $content, $array);

$i = 1;
$limit = count($array[0]);

echo $array[0][4]; //outside loop

while ( $i <= $limit) {
  echo $array[0][4]; // inside loop
  $i++;
}
return $content;
}
add_action('the_content', 'thing', 50);

This still isn't great code as it assumes the array is 5 members and repeats the same value each time it loops. Let's rewrite the while loop into a for:

for( $i = 0; $i < $limit; $i++ ) {
  echo $array[0][$i]; // inside loop
}
8
  • You can use is_array to be sure $array is actually an array. php.net/manual/en/function.is-array.php
    – Welcher
    Commented Jul 18, 2017 at 12:49
  • When I use var_dump($array); it shows that it's a multidimensional array which contains two arrays and each of those two arrays contain 5 keys Commented Jul 18, 2017 at 13:01
  • Ok, but why are you trying to get the 4th value specifically?
    – Chris Cox
    Commented Jul 18, 2017 at 13:02
  • Also, the third parameter of preg_match_all() is an array php.net/manual/en/function.preg-match-all.php Commented Jul 18, 2017 at 13:05
  • On line 8 you set the value of $array to $array[0][4]. You do the same again at line 12 within the while loop, which would refer to $array[0][4][0][4] which doesn't exist in the original array.
    – Chris Cox
    Commented Jul 18, 2017 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.