PHP: Undefined offset

2020-02-13 02:01发布

问题:

On some pages, i receive the error:

PHP Notice: Undefined offset: 1 in /var/www/example.com/includes/head.php on line 23

Here is the code:

if ($r)
{

    list($r1, $r2)=explode(" ", $r[0],2);
    $r1 = mb_strtolower($r1);
    $r3 = " ";
    $r2 = $r3.$r2;
    $r[0] = $r1.$r2;
    $page_title_f = $r[0]." some text";
    $page_title_s = "some text ";
    $page_title = $page_title_s.$page_title_f;

}

Line 23 with error:

list($r1, $r2)=explode(" ", $r[0],2);

Could you help to understand what could be the problem?

Update

Thanks all for the help! I partially solved the problem.

$r is row in the database. The script takes a string and starts to manipulate. Converts uppercase letters to lowercase. And as I understand it, the string must have a space otherwise gets out an error "Undefined offset". Because the script tries to find the first space, and then merge the word before the first space, and the space together with everything that appears after a space. (: I don't understand why he does and there is no way out of this situation if the space in the string no, he just throws an error. ): In general it is a very old and poor engine web store called Shop-Script. Post a full listing of the file, maybe it will be clearer.

http://pastebin.com/Pz1TKpr3

回答1:

The undefined index error you are receiving is because the offset that you're trying to explode in the variable ($r) doesn't exist.

You can check what $r is by doing the following:

print_r($r);

or

var_dump($r);

You'll need to show what $r holds before debugging this issue further.

But a guess would be that your $r variable is a string that you're trying to explode, but you're trying to access it as an array.

What happens if you explode it like this:

list($r1, $r2) = explode(' ', $r, 2);


回答2:

list($r1, $r2) = explode(" ", $r[0],2);

When supplied with two variables, list() will need an array with at least 2 items.
However, as the error you mentioned indicates, your explode() call seems to return an array with only one item.

You will have to check the contents of $r[0] to make sure it actually contains your splitting character or manually assign $r1 and $r2 with sanity checks.



回答3:

Try:

$words = explode(' ', $r[0], 2);
$r1 = isset($words[0]) ? $words[0] : '';
$r2 = isset($words[1]) ? $words[1] : '';

If $r[0] doesn't contain 2 words, your code will get an error because explode() will return an array with just one element, and you can't assign that to two variables. This code tests whether the word exists before trying to assign it.



回答4:

My answer is not specific to your code. For others who get this error while trying to use specific elements of array you created, try indexing your elements while creating the array itself. This helps you to explode/print a specific element/do whatever you want with the array.