Php ошибка undefined offset

I am receiving the following error in PHP

Notice undefined offset 1: in C:wampwwwincludesimdbgrabber.php line 36

Here is the PHP code that causes it:

<?php

# ...

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

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

What does the error mean?

Cœur's user avatar

Cœur

36.9k25 gold badges193 silver badges262 bronze badges

asked Mar 24, 2010 at 14:02

user272899's user avatar

1

If preg_match did not find a match, $matches is an empty array. So you should check if preg_match found an match before accessing $matches[0], for example:

function get_match($regex,$content)
{
    if (preg_match($regex,$content,$matches)) {
        return $matches[0];
    } else {
        return null;
    }
}

answered Mar 24, 2010 at 14:05

Gumbo's user avatar

GumboGumbo

640k109 gold badges775 silver badges843 bronze badges

2

How to reproduce this error in PHP:

Create an empty array and ask for the value given a key like this:

php> $foobar = array();

php> echo gettype($foobar);
array

php> echo $foobar[0];

PHP Notice:  Undefined offset: 0 in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) : 
eval()'d code on line 1

What happened?

You asked an array to give you the value given a key that it does not contain. It will give you the value NULL then put the above error in the errorlog.

It looked for your key in the array, and found undefined.

How to make the error not happen?

Ask if the key exists first before you go asking for its value.

php> echo array_key_exists(0, $foobar) == false;
1

If the key exists, then get the value, if it doesn’t exist, no need to query for its value.

answered Feb 15, 2014 at 4:28

Eric Leschinski's user avatar

Eric LeschinskiEric Leschinski

145k95 gold badges412 silver badges332 bronze badges

1

Undefined offset error in PHP is Like ‘ArrayIndexOutOfBoundException’ in Java.

example:

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

error: Undefined offset 2

It means you’re referring to an array key that doesn’t exist. «Offset»
refers to the integer key of a numeric array, and «index» refers to the
string key of an associative array.

answered Jan 25, 2015 at 13:12

pathe.kiran's user avatar

pathe.kiranpathe.kiran

2,4241 gold badge20 silver badges27 bronze badges

1

Undefined offset means there’s an empty array key for example:

$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];

You can solve the problem using a loop (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] = "";
}

Martin Tournoij's user avatar

answered Jun 10, 2016 at 22:06

Felix Siaw-Yeboah's user avatar

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    The Offset that does not exist in an array then it is called as an undefined offset. Undefined offset error is similar to ArrayOutOfBoundException in Java. If we access an index that does not exist or an empty offset, it will lead to an undefined offset error.
    Example: Following PHP code explains how we can access array elements. If the accessed index is not present then it gives an undefined offset error.
     

    php

    <?php 

    $students = array(

        0 => 'Rohan',

        1 => 'Arjun',

        2 => 'Niharika'

    );

    echo $students[0];

    echo $students[5];

    echo $students[key];

    ?>

    Output: 
     

    There are some methods to avoid undefined offset error that are discussed below: 
     

    • isset() function: This function checks whether the variable is set and is not equal to null. It also checks if array or array key has null value or not.
      Example: 
       

    php

    <?php 

    $students = array(

        0 => 'Rohan',

        1 => 'Arjun',

        2 => 'Niharika'

    );

    if(isset($students[5])) {

        echo $students[5];

    }

    else {

        echo "Index not present";

    }

    ?>

    Output:

    Index not present
    • empty() function: This function checks whether the variable or index value in an array is empty or not.

    php

    <?php 

    $students = array(

        0 => 'Rohan',

        1 => 'Arjun',

        2 => 'Niharika'

    );

    if(!empty($students[5])) {

        echo $students[5];

    }

    else {

        echo "Index not present";

    }

    ?>

    Output:

    Index not present
  • array_key_exists() function for associative arrays: Associative array stores data in the form of key-value pair and for every key there exists a value. The array_key_exists() function checks whether the specified key is present in the array or not.
    Example:

    php

    <?php 

    function Exists($index, $array) { 

        if (array_key_exists($index, $array)) { 

            echo "Key Found"

        

        else

            echo "Key not Found"

        

    $array = array(

        "ram" => 25, 

        "krishna" => 10, 

        "aakash" => 20

    ); 

    $index = "aakash"

    print_r(Exists($index, $array)); 

    ?>

    Output:

    Key Found

    PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

  • Last Updated :
    31 Jul, 2021

    Like Article

    Save Article

    Notice: Undefined offset

    This error means that within your code, there is an array and its keys. But you may be trying to use the key of an array which is not set.

    The error can be avoided by using the isset() method. This method will check whether the declared array key has null value or not. If it does it returns false else it returns true for all cases.

    This type of error occurs with arrays when we use the key of an array, which is not set.

    Notice: Undefined offset error in PHP

    In the following, given an example, we are displaying the value store in array key 1, but we did not set while declaring array “$colorarray.”

    Error Example:

    <?php
    // Declare an array with key 2, 3, 4, 5
    $colorarray = array(2=>'Red',3=>'Green',4=>'Blue',5=>'Yellow');
    // Printing the value of array at offset 1.
    echo $colorarray[1];
    ?>

    Output:

    Notice: Undefined offset: 1 in index.php on line 5

    Here are two ways to deal with such notices.

    1. Resolve such notices.
    2. Ignore such notices.

    Fix Notice: Undefined offset by using isset() Function

    Check the value of offset array with function isset(), empty(), and array_key_exists() to check if key exist or not.

    Example:

    <?php
    $colorarray = array(2=>'Red',3=>'Green',4=>'Blue',5=>'Yellow');
    // isset() function to check value at offset 1 of array
    if(isset($colorarray[1])){echo $colorarray[1];}
    // empty() function to check value at offset 1 of array
    if(!empty($colorarray[1])){echo $colorarray[1];}
    // array_key_exists() of check if key 1 is exist or not
    echo array_key_exists(1, $colorarray);
    ?>

    How to Ignore PHP Notice: Undefined offset?

    You can ignore this notice by disabling reporting of notice with option error_reporting.

    1. Disable Display Notice in php.ini file

    Open php.ini file in your favourite editor and search for text “error_reporting” the default value is E_ALL. You can change it to E_ALL & ~E_NOTICE.

    By default:

    error_reporting = E_ALL

    Change it to:

    error_reporting = E_ALL & ~E_NOTICE

    Now your PHP compiler will show all errors except ‘Notice.’

    2. Disable Display Notice in PHP Code

    If you don’t have access to make changes in the php.ini file, In this case, you need to disable the notice by adding the following code on the top of your php page.

    <?php error_reporting (E_ALL ^ E_NOTICE); ?>

    Now your PHP compiler will show all errors except ‘Notice.’

    Before discovering how to avoid the PHP undefined offset error, let’s see what it is. The undefined offset is the one that doesn’t exist inside an array. An attempt to access such an index will lead to an error, which is known as undefined offset error.

    Let’s see an example:

    <?php
    
    // Declare and initialize an array
    // $students = ['Ann', 'Jennifer', 'Mary']
    $students = [
        0 => 'Ann',
        1 => 'Jennifer',
        2 => 'Mary',
    ];
    
    // Leyla
    echo $students[0];
    
    // ERROR: Undefined offset: 5
    echo $students[5];
    
    // ERROR: Undefined index: key
    echo $students[key];
    
    ?>

    Below, we will show you several methods to avoid the undefined offset error.

    This function allows checking if the variable is set and is not null.

    The example of using the isset function to avoid undefined offset error is as follows:

    <?php
    
    // Declare and initialize an array
    // $students = ['Ann', 'Jennifer', 'Mary']
    $students = [
        0 => 'Ann',
        1 => 'Jennifer',
        2 => 'Mary',
    ];
    
    if (isset($students[5])) {
        echo $students[5];
    } else {
        echo "Index not present";
    }
    
    ?>
    Index not present

    The empty() function is used for checking if the variable or the index value inside an array is empty.

    Here is an example:

    <?php
    
    // Declare and initialize an array
    // $students = ['Rohan', 'Arjun', 'Niharika']
    $students = [
      0 => 'Ann',
      1 => 'Jennifer',
      2 => 'Mary',
    ];
    
    if (!empty($students[5])) {
      echo $students[5];
    } else {
      echo "Index not present";
    }
    
    ?>
    Index not present

    This function is used for associative arrays that store data in the key-value pair form, and there is a value for each key.

    The array_key_exists function is used for testing if a particular key exists in an array or not.

    Here is an example:

    <?php
    // PHP program to illustrate the use
    // of array_key_exists() function
    
    function Exists($index, $array)
    {
        if (array_key_exists($index, $array)) {
            echo "Key Found";
        } else {
            echo "Key not Found";
        }
    }
    
    $array = [
        "john" => 25,
        "david" => 10,
        "jack" => 20,
    ];
    
    $index = "jack";
    
    print_r(Exists($index, $array));
    
    ?>
    Key Found

    Приветствую! Посмотрел в логе есть несколько ошибок, помогите исправить пожалуйста, спасибо!

    error.log

    [Sun Jan 27 08:42:09.476142 2019] [fcgid:warn] [pid 28535] mod_fcgid: stderr: PHP Notice: Only variables should be passed by reference in /var/www/mysite/data/www/mysite.io/core/Classes/Lang.php on line 90

    [Sun Jan 27 08:42:09.476145 2019] [fcgid:warn] [pid 28535] mod_fcgid: stderr: PHP Notice: Undefined offset: 1 in /var/www/mysite/data/www/mysite.io/core/Classes/Router.php on line 97

    [Sun Jan 27 08:42:18.984905 2019] [fcgid:warn] [pid 28533] mod_fcgid: stderr: PHP Notice: Undefined offset: 1 in /var/www/mysite/data/www/mysite.io/core/Classes/Router.php on line 29, referer: mysite.io/en/

    [Sun Jan 27 08:42:18.984922 2019] [fcgid:warn] [pid 28533] mod_fcgid: stderr: PHP Notice: Undefined offset: 1 in /var/www/mysite/data/www/mysite.io/core/Classes/Router.php on line 97, referer: mysite.io/en/

    [Sun Jan 27 08:42:26.384808 2019] [fcgid:warn] [pid 28531] mod_fcgid: stderr: PHP Notice: Undefined offset: 1 in /var/www/mysite/data/www/mysite.io/core/Classes/Router.php on line 29, referer: mysite.io/ru/

    [Sun Jan 27 08:42:26.384831 2019] [fcgid:warn] [pid 28531] mod_fcgid: stderr: PHP Notice: Undefined offset: 1 in /var/www/mysite/data/www/mysite.io/core/Classes/Router.php on line 97, referer: mysite.io/ru/

    Файл Router.php

    protected function prepare()
     {
        $url = trim($this->server->get(static::SERVER_KEY), '/');
        @list($root, $query) = explode('?', $url);
    
        list($lang, $requestUrl) = explode('/', $root, 2); //line 29
    
        if($this->server->is('POST')) {
            $requestUrl = $lang;
        } else {
            if(in_array($lang, [Lang::LANG_RU, Lang::LANG_EN]) && $lang == config('language.default')) {
                header('Location: /' . $requestUrl);
                die;
            }
    
            if(
                !in_array($lang, [Lang::LANG_RU, Lang::LANG_EN])
            ) {
                $requestUrl = $url;
                $lang = config('language.default');
            }
    
            if(
                in_array($lang, [Lang::LANG_RU, Lang::LANG_EN])
                && $lang != lang()->lang()
            ) {
                lang()->setLanguage($lang);
    
                if($lang == config('language.default')) {
                    header('Location: /' . $requestUrl);
                } else {
                    header('Location: /' . lang()->lang() . '/' . $requestUrl);
                }
    
                die;
            }
        }
    
        $this->url = $requestUrl;
        $this->full_url = $url;
        $this->query = $query;
        $this->params = $this->parseQuery($query);
        $this->arguments = $this->parseArguments($url);
    }
    
    
    
    protected function parseArguments($url)
     {
        $segments = explode('/', $url);
    
        $data = [];
        foreach ($segments as $segment) {
            if(in_array($segment, [Lang::LANG_RU, Lang::LANG_EN])) { //line 97
                continue;
            }
    
            $data[] = $segment;
        }
        return $data;
    }

    Файл Lang.php

    protected function parseFromRaw($raw)
    {
    $lang = array_shift(explode(',', $raw)); //line 90
    
    return in_array($lang, array_keys($this->getLanguagesList()))
        ? $lang
        : $this->defaultLanguage();
    }

    Понравилась статья? Поделить с друзьями:
  • Php ошибка headers already sent by
  • Php ошибка eval d code
  • Php ошибка 301
  • Php ошибка 500 как вывести
  • Php отобразить все ошибки