51

PHP で次のエラーが表示されます

C:\wamp\www\includes\imdbgrabber.php 行 36 の未定義のオフセット 1: に注意してください。

それを引き起こすPHPコードは次のとおりです。

<?php

# ...

function get_match($regex, $content)  
{  
    preg_match($regex,$content,$matches);     

    return $matches[1]; // ERROR HAPPENS HERE
}

エラーの意味は何ですか?

4

4 に答える 4

44

preg_match一致が見つからなかった場合$matchesは、空の配列です。したがって、preg_matchにアクセスする前に、一致するものが見つかったかどうかを確認する必要があります$matches[0]。次に例を示します。

function get_match($regex,$content)
{
    if (preg_match($regex,$content,$matches)) {
        return $matches[0];
    } else {
        return null;
    }
}
于 2010-03-24T14:05:37.397 に答える
5

PHP の未定義のオフセット エラーは、Javaの 'ArrayIndexOutOfBoundException'に似ています。

例:

<?php
$arr=array('Hello','world');//(0=>Hello,1=>world)
echo $arr[2];
?>

エラー: 未定義のオフセット 2

存在しない配列キーを参照していることを意味します。「オフセット」は数値配列の整数キーを指し、「インデックス」は連想配列の文字列キーを指します。

于 2015-01-25T13:12:37.577 に答える
1

未定義のオフセットは、たとえば空の配列キーがあることを意味します。

$a = array('Felix','Jon','Java');

// This will result in an "Undefined offset" because the size of the array
// is three (3), thus, 0,1,2 without 3
echo $a[3];

ループ (while) を使用して問題を解決できます。

$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
    // Increase count by 1, thus, $i=1
    $i++;

    $groupname[$i] = base64_decode(base64_decode($row['groupname']));

    // Set the first position of the array to null or empty
    $groupname[0] = "";
}
于 2016-06-10T22:06:57.150 に答える