Ошибка undefined offset 0

I am getting this PHP error, what does it mean? Notice: Undefined offset: 0 in C:xampphtdocsmywebsitereddit_vote_tutsrcvotes.php on line 41 From this code: <?php include("config.php")...

I am getting this PHP error, what does it mean?

Notice: Undefined offset: 0 in 
C:xampphtdocsmywebsitereddit_vote_tutsrcvotes.php on line 41

From this code:

<?php 
include("config.php"); 

function getAllVotes($id) 
{ 
    $votes = array(); 
    $q = "SELECT * FROM entries WHERE id = $id"; 
    $r = mysql_query($q); 
    if(mysql_num_rows($r)==1)//id found in the table 
    { 
        $row = mysql_fetch_assoc($r); 
        $votes[0] = $row['votes_up']; 
        $votes[1] = $row['votes_down']; 
    } 
    return $votes; 
} 

function getEffectiveVotes($id) 
{ 
        $votes = getAllVotes($id); 
        $effectiveVote = $votes[0] - $votes[1];    //ERROR THROWN HERE
        return $effectiveVote; 
} 

$id = $_POST['id']; 
$action = $_POST['action']; 

//get the current votes 
$cur_votes = getAllVotes($id); 

//ok, now update the votes 

if($action=='vote_up') //voting up 
{ 

    $votes_up = $cur_votes[0]+1;     //AND ERROR THROWN HERE


    $q = "UPDATE threads SET votes_up = $votes_up WHERE id = $id"; 
} 
elseif($action=='vote_down')
{ 
    $votes_down = $cur_votes[1]+1; 
    $q = "UPDATE threads SET votes_down = $votes_down WHERE id = $id"; 
} 

$r = mysql_query($q); 
if($r)
{ 
    $effectiveVote = getEffectiveVotes($id); 
    echo $effectiveVote." votes"; 
} 
elseif(!$r) //voting failed 
{ 
    echo "Failed!"; 
} 
?>

Eric Leschinski's user avatar

asked Jul 1, 2011 at 14:51

louismoore18's user avatar

4

You are asking for the value at key 0 of $votes. It is an array that does not contain that key.

The array $votes is not set, so when PHP is trying to access the key 0 of the array, it encounters an undefined offset for [0] and [1] and throws the error.

If you have an array:

$votes = array('1','2','3');

We can now access:

$votes[0];
$votes[1];
$votes[2];

If we try and access:

$votes[3];

We will get the error «Notice: Undefined offset: 3»

toddmo's user avatar

toddmo

19.8k13 gold badges91 silver badges102 bronze badges

answered Jul 1, 2011 at 14:55

YonoRan's user avatar

YonoRanYonoRan

1,6989 silver badges7 bronze badges

6

first, check that the array actually exists, you could try something like

if (isset($votes)) {
   // Do bad things to the votes array
}

Mostafa Norzade's user avatar

answered Mar 24, 2014 at 8:36

Agg-rey Muhebwa's user avatar

This answer helped me https://stackoverflow.com/a/18880670/1821607
The reason of crush — index 0 wasn’t set. Simple $array = $array + array(null) did the trick. Or you should check whether array element on index 0 is set via isset($array[0]). The second variant is the best approach for me.

Community's user avatar

answered Dec 1, 2015 at 10:17

Dmitrii Malyshev's user avatar

Use print_r($votes); to inspect the array $votes, you will see that key 0 does not exist there. It will return NULL and throw that error.

Eric Leschinski's user avatar

answered Jul 23, 2011 at 9:59

Giulio Prisco's user avatar

0

getAllVotes() isn’t returning an array with the indexes 0 or 1. Make sure it’s returning the data you want by calling var_dump() on the result.

answered Jul 1, 2011 at 14:54

Tim Cooper's user avatar

Tim CooperTim Cooper

156k38 gold badges327 silver badges277 bronze badges

I encountered this as well and the solution is simple, dont hardcode the array index position in your code.
Instead of
$data[0]['somekey'] do
foreach($data as $data_item)
{
echo $data_item['somekey'];
}

If there is an array or more you can perform your desired action inside the loop, but if it’s undefined it will not bring an error. you can also add other checks on top of that.
You could also add a variable and increment it in a for in loop to limit your looping if you want only the first positions or something.

answered Jul 29, 2018 at 12:50

Mihai's user avatar

MihaiMihai

821 silver badge6 bronze badges

As explained it happens because there is no data in the $cur_votes[0] and hence it throws an error.

To ensure your code works fine, before performing "$votes_up = $cur_votes[0]+1;" echo the $cur_votes[0] value to see if there is any value stored or not.

Surely, there is no value stored.

Mostafa Norzade's user avatar

answered Mar 27, 2013 at 9:00

Espanta's user avatar

EspantaEspanta

1,0501 gold badge17 silver badges27 bronze badges

function getEffectiveVotes($id) 

According to the function header, there is only one parameter variable ($id).
Thus, on line 27, the votes[] array is undefined and out of scope. You need to add another
parameter value to the function header so that function getEffectiveVotes() knows to expect two parameters. I’m rusty, but something like this would work.

function getEffectiveVotes($id, $votes)

I’m not saying this is how it should be done, but you might want to research how PHP
passes its arrays and decide if you need to explicitly state to pass it by reference

function getEffectiveVotes($id &$votes)    <---I forget, no time to look it up right now.

Lastly, call function getEffectiveVotes() with both arguments wherever it is supposed to be called.

Cheers.

answered Jun 21, 2013 at 3:46

Anthony Rutledge's user avatar

Anthony RutledgeAnthony Rutledge

6,5321 gold badge36 silver badges44 bronze badges

As you might have already about knew the error. This is due to trying to access the empty array or trying to access the value of empty key of array. In my project, I am dealing with this error with counting the array and displaying result.

You can do it like this:

if(count($votes) == '0'){

    echo 'Sorry, no votes are available at the moment.';
}
else{
    //do the stuff with votes
}

count($votes) counts the $votes array. If it is equal to zero (0), you can display your custom message or redirect to certain page else you can do stuff with $votes. In this way you can remove the Notice: Undefined offset: 0 in notice in PHP.

answered Feb 19, 2016 at 5:33

VijayRana's user avatar

VijayRanaVijayRana

9131 gold badge12 silver badges35 bronze badges

If you leave out the brackets then PHP will assign the keys by default.

Try this:

$votes = $row['votes_up']; 
$votes = $row['votes_down']; 

answered Sep 22, 2014 at 19:07

David's user avatar

DavidDavid

4292 gold badges5 silver badges14 bronze badges

In my case it was a simple type

$_SESSION['role' == 'ge']

I was missing the correct closing bracket

$_SESSION['role'] == 'ge'

answered Nov 23, 2018 at 7:44

Hammad Khan's user avatar

Hammad KhanHammad Khan

16k16 gold badges111 silver badges134 bronze badges

If you are using dompdf/dompdf and error occure in vendor/dompdf/dompdf/src/Cellmap.php then
It looks like we’re using the wrong frame id in the update_row_group method. Initial testing seems to confirm this. Though that may be because this is strictly a paged table issue and not too many of the documents in my test bed have paged tables.

Can you try changing line 800 to:

$r_rows = $this->_frames[$g_key][«rows»];
($g_key instead of $r_key)

https://github.com/dompdf/dompdf/issues/1295

answered Dec 19, 2018 at 7:51

Madhavi Khatal's user avatar

Use mysql row instead

mysql_fetch_row($r)

Meanwhile consider using mysqli or PDO

?>

Try seeding data with command: php artisan db:seed.

sssurii's user avatar

sssurii

7284 silver badges15 bronze badges

answered Jul 26, 2021 at 4:09

Nam Sama's user avatar

Nam SamaNam Sama

3253 silver badges5 bronze badges

0

its just a warning use:

error_reporting(0);

it shows when we do not initialize array and direct assigning value to indexes.

somefunction{
$raja[0]="this";
$raja[1]="that";
}

instead :

somefunction{
$raja=array(0=>'this',1='that');
//or
$raja=array("this","that");
}

it just notification, do not generate any output error or any unexpected output.

answered Aug 27, 2014 at 7:59

Teerath Kumar's user avatar

3

I am getting this PHP error, what does it mean?

Notice: Undefined offset: 0 in 
C:xampphtdocsmywebsitereddit_vote_tutsrcvotes.php on line 41

From this code:

<?php 
include("config.php"); 

function getAllVotes($id) 
{ 
    $votes = array(); 
    $q = "SELECT * FROM entries WHERE id = $id"; 
    $r = mysql_query($q); 
    if(mysql_num_rows($r)==1)//id found in the table 
    { 
        $row = mysql_fetch_assoc($r); 
        $votes[0] = $row['votes_up']; 
        $votes[1] = $row['votes_down']; 
    } 
    return $votes; 
} 

function getEffectiveVotes($id) 
{ 
        $votes = getAllVotes($id); 
        $effectiveVote = $votes[0] - $votes[1];    //ERROR THROWN HERE
        return $effectiveVote; 
} 

$id = $_POST['id']; 
$action = $_POST['action']; 

//get the current votes 
$cur_votes = getAllVotes($id); 

//ok, now update the votes 

if($action=='vote_up') //voting up 
{ 

    $votes_up = $cur_votes[0]+1;     //AND ERROR THROWN HERE


    $q = "UPDATE threads SET votes_up = $votes_up WHERE id = $id"; 
} 
elseif($action=='vote_down')
{ 
    $votes_down = $cur_votes[1]+1; 
    $q = "UPDATE threads SET votes_down = $votes_down WHERE id = $id"; 
} 

$r = mysql_query($q); 
if($r)
{ 
    $effectiveVote = getEffectiveVotes($id); 
    echo $effectiveVote." votes"; 
} 
elseif(!$r) //voting failed 
{ 
    echo "Failed!"; 
} 
?>

Eric Leschinski's user avatar

asked Jul 1, 2011 at 14:51

louismoore18's user avatar

4

You are asking for the value at key 0 of $votes. It is an array that does not contain that key.

The array $votes is not set, so when PHP is trying to access the key 0 of the array, it encounters an undefined offset for [0] and [1] and throws the error.

If you have an array:

$votes = array('1','2','3');

We can now access:

$votes[0];
$votes[1];
$votes[2];

If we try and access:

$votes[3];

We will get the error «Notice: Undefined offset: 3»

toddmo's user avatar

toddmo

19.8k13 gold badges91 silver badges102 bronze badges

answered Jul 1, 2011 at 14:55

YonoRan's user avatar

YonoRanYonoRan

1,6989 silver badges7 bronze badges

6

first, check that the array actually exists, you could try something like

if (isset($votes)) {
   // Do bad things to the votes array
}

Mostafa Norzade's user avatar

answered Mar 24, 2014 at 8:36

Agg-rey Muhebwa's user avatar

This answer helped me https://stackoverflow.com/a/18880670/1821607
The reason of crush — index 0 wasn’t set. Simple $array = $array + array(null) did the trick. Or you should check whether array element on index 0 is set via isset($array[0]). The second variant is the best approach for me.

Community's user avatar

answered Dec 1, 2015 at 10:17

Dmitrii Malyshev's user avatar

Use print_r($votes); to inspect the array $votes, you will see that key 0 does not exist there. It will return NULL and throw that error.

Eric Leschinski's user avatar

answered Jul 23, 2011 at 9:59

Giulio Prisco's user avatar

0

getAllVotes() isn’t returning an array with the indexes 0 or 1. Make sure it’s returning the data you want by calling var_dump() on the result.

answered Jul 1, 2011 at 14:54

Tim Cooper's user avatar

Tim CooperTim Cooper

156k38 gold badges327 silver badges277 bronze badges

I encountered this as well and the solution is simple, dont hardcode the array index position in your code.
Instead of
$data[0]['somekey'] do
foreach($data as $data_item)
{
echo $data_item['somekey'];
}

If there is an array or more you can perform your desired action inside the loop, but if it’s undefined it will not bring an error. you can also add other checks on top of that.
You could also add a variable and increment it in a for in loop to limit your looping if you want only the first positions or something.

answered Jul 29, 2018 at 12:50

Mihai's user avatar

MihaiMihai

821 silver badge6 bronze badges

As explained it happens because there is no data in the $cur_votes[0] and hence it throws an error.

To ensure your code works fine, before performing "$votes_up = $cur_votes[0]+1;" echo the $cur_votes[0] value to see if there is any value stored or not.

Surely, there is no value stored.

Mostafa Norzade's user avatar

answered Mar 27, 2013 at 9:00

Espanta's user avatar

EspantaEspanta

1,0501 gold badge17 silver badges27 bronze badges

function getEffectiveVotes($id) 

According to the function header, there is only one parameter variable ($id).
Thus, on line 27, the votes[] array is undefined and out of scope. You need to add another
parameter value to the function header so that function getEffectiveVotes() knows to expect two parameters. I’m rusty, but something like this would work.

function getEffectiveVotes($id, $votes)

I’m not saying this is how it should be done, but you might want to research how PHP
passes its arrays and decide if you need to explicitly state to pass it by reference

function getEffectiveVotes($id &$votes)    <---I forget, no time to look it up right now.

Lastly, call function getEffectiveVotes() with both arguments wherever it is supposed to be called.

Cheers.

answered Jun 21, 2013 at 3:46

Anthony Rutledge's user avatar

Anthony RutledgeAnthony Rutledge

6,5321 gold badge36 silver badges44 bronze badges

As you might have already about knew the error. This is due to trying to access the empty array or trying to access the value of empty key of array. In my project, I am dealing with this error with counting the array and displaying result.

You can do it like this:

if(count($votes) == '0'){

    echo 'Sorry, no votes are available at the moment.';
}
else{
    //do the stuff with votes
}

count($votes) counts the $votes array. If it is equal to zero (0), you can display your custom message or redirect to certain page else you can do stuff with $votes. In this way you can remove the Notice: Undefined offset: 0 in notice in PHP.

answered Feb 19, 2016 at 5:33

VijayRana's user avatar

VijayRanaVijayRana

9131 gold badge12 silver badges35 bronze badges

If you leave out the brackets then PHP will assign the keys by default.

Try this:

$votes = $row['votes_up']; 
$votes = $row['votes_down']; 

answered Sep 22, 2014 at 19:07

David's user avatar

DavidDavid

4292 gold badges5 silver badges14 bronze badges

In my case it was a simple type

$_SESSION['role' == 'ge']

I was missing the correct closing bracket

$_SESSION['role'] == 'ge'

answered Nov 23, 2018 at 7:44

Hammad Khan's user avatar

Hammad KhanHammad Khan

16k16 gold badges111 silver badges134 bronze badges

If you are using dompdf/dompdf and error occure in vendor/dompdf/dompdf/src/Cellmap.php then
It looks like we’re using the wrong frame id in the update_row_group method. Initial testing seems to confirm this. Though that may be because this is strictly a paged table issue and not too many of the documents in my test bed have paged tables.

Can you try changing line 800 to:

$r_rows = $this->_frames[$g_key][«rows»];
($g_key instead of $r_key)

https://github.com/dompdf/dompdf/issues/1295

answered Dec 19, 2018 at 7:51

Madhavi Khatal's user avatar

Use mysql row instead

mysql_fetch_row($r)

Meanwhile consider using mysqli or PDO

?>

Try seeding data with command: php artisan db:seed.

sssurii's user avatar

sssurii

7284 silver badges15 bronze badges

answered Jul 26, 2021 at 4:09

Nam Sama's user avatar

Nam SamaNam Sama

3253 silver badges5 bronze badges

0

its just a warning use:

error_reporting(0);

it shows when we do not initialize array and direct assigning value to indexes.

somefunction{
$raja[0]="this";
$raja[1]="that";
}

instead :

somefunction{
$raja=array(0=>'this',1='that');
//or
$raja=array("this","that");
}

it just notification, do not generate any output error or any unexpected output.

answered Aug 27, 2014 at 7:59

Teerath Kumar's user avatar

3

I am getting this PHP error, what does it mean?

Notice: Undefined offset: 0 in 
C:xampphtdocsmywebsitereddit_vote_tutsrcvotes.php on line 41

From this code:

<?php 
include("config.php"); 

function getAllVotes($id) 
{ 
    $votes = array(); 
    $q = "SELECT * FROM entries WHERE id = $id"; 
    $r = mysql_query($q); 
    if(mysql_num_rows($r)==1)//id found in the table 
    { 
        $row = mysql_fetch_assoc($r); 
        $votes[0] = $row['votes_up']; 
        $votes[1] = $row['votes_down']; 
    } 
    return $votes; 
} 

function getEffectiveVotes($id) 
{ 
        $votes = getAllVotes($id); 
        $effectiveVote = $votes[0] - $votes[1];    //ERROR THROWN HERE
        return $effectiveVote; 
} 

$id = $_POST['id']; 
$action = $_POST['action']; 

//get the current votes 
$cur_votes = getAllVotes($id); 

//ok, now update the votes 

if($action=='vote_up') //voting up 
{ 

    $votes_up = $cur_votes[0]+1;     //AND ERROR THROWN HERE


    $q = "UPDATE threads SET votes_up = $votes_up WHERE id = $id"; 
} 
elseif($action=='vote_down')
{ 
    $votes_down = $cur_votes[1]+1; 
    $q = "UPDATE threads SET votes_down = $votes_down WHERE id = $id"; 
} 

$r = mysql_query($q); 
if($r)
{ 
    $effectiveVote = getEffectiveVotes($id); 
    echo $effectiveVote." votes"; 
} 
elseif(!$r) //voting failed 
{ 
    echo "Failed!"; 
} 
?>

Eric Leschinski's user avatar

asked Jul 1, 2011 at 14:51

louismoore18's user avatar

4

You are asking for the value at key 0 of $votes. It is an array that does not contain that key.

The array $votes is not set, so when PHP is trying to access the key 0 of the array, it encounters an undefined offset for [0] and [1] and throws the error.

If you have an array:

$votes = array('1','2','3');

We can now access:

$votes[0];
$votes[1];
$votes[2];

If we try and access:

$votes[3];

We will get the error «Notice: Undefined offset: 3»

toddmo's user avatar

toddmo

19.8k13 gold badges91 silver badges102 bronze badges

answered Jul 1, 2011 at 14:55

YonoRan's user avatar

YonoRanYonoRan

1,6989 silver badges7 bronze badges

6

first, check that the array actually exists, you could try something like

if (isset($votes)) {
   // Do bad things to the votes array
}

Mostafa Norzade's user avatar

answered Mar 24, 2014 at 8:36

Agg-rey Muhebwa's user avatar

This answer helped me https://stackoverflow.com/a/18880670/1821607
The reason of crush — index 0 wasn’t set. Simple $array = $array + array(null) did the trick. Or you should check whether array element on index 0 is set via isset($array[0]). The second variant is the best approach for me.

Community's user avatar

answered Dec 1, 2015 at 10:17

Dmitrii Malyshev's user avatar

Use print_r($votes); to inspect the array $votes, you will see that key 0 does not exist there. It will return NULL and throw that error.

Eric Leschinski's user avatar

answered Jul 23, 2011 at 9:59

Giulio Prisco's user avatar

0

getAllVotes() isn’t returning an array with the indexes 0 or 1. Make sure it’s returning the data you want by calling var_dump() on the result.

answered Jul 1, 2011 at 14:54

Tim Cooper's user avatar

Tim CooperTim Cooper

156k38 gold badges327 silver badges277 bronze badges

I encountered this as well and the solution is simple, dont hardcode the array index position in your code.
Instead of
$data[0]['somekey'] do
foreach($data as $data_item)
{
echo $data_item['somekey'];
}

If there is an array or more you can perform your desired action inside the loop, but if it’s undefined it will not bring an error. you can also add other checks on top of that.
You could also add a variable and increment it in a for in loop to limit your looping if you want only the first positions or something.

answered Jul 29, 2018 at 12:50

Mihai's user avatar

MihaiMihai

821 silver badge6 bronze badges

As explained it happens because there is no data in the $cur_votes[0] and hence it throws an error.

To ensure your code works fine, before performing "$votes_up = $cur_votes[0]+1;" echo the $cur_votes[0] value to see if there is any value stored or not.

Surely, there is no value stored.

Mostafa Norzade's user avatar

answered Mar 27, 2013 at 9:00

Espanta's user avatar

EspantaEspanta

1,0501 gold badge17 silver badges27 bronze badges

function getEffectiveVotes($id) 

According to the function header, there is only one parameter variable ($id).
Thus, on line 27, the votes[] array is undefined and out of scope. You need to add another
parameter value to the function header so that function getEffectiveVotes() knows to expect two parameters. I’m rusty, but something like this would work.

function getEffectiveVotes($id, $votes)

I’m not saying this is how it should be done, but you might want to research how PHP
passes its arrays and decide if you need to explicitly state to pass it by reference

function getEffectiveVotes($id &$votes)    <---I forget, no time to look it up right now.

Lastly, call function getEffectiveVotes() with both arguments wherever it is supposed to be called.

Cheers.

answered Jun 21, 2013 at 3:46

Anthony Rutledge's user avatar

Anthony RutledgeAnthony Rutledge

6,5321 gold badge36 silver badges44 bronze badges

As you might have already about knew the error. This is due to trying to access the empty array or trying to access the value of empty key of array. In my project, I am dealing with this error with counting the array and displaying result.

You can do it like this:

if(count($votes) == '0'){

    echo 'Sorry, no votes are available at the moment.';
}
else{
    //do the stuff with votes
}

count($votes) counts the $votes array. If it is equal to zero (0), you can display your custom message or redirect to certain page else you can do stuff with $votes. In this way you can remove the Notice: Undefined offset: 0 in notice in PHP.

answered Feb 19, 2016 at 5:33

VijayRana's user avatar

VijayRanaVijayRana

9131 gold badge12 silver badges35 bronze badges

If you leave out the brackets then PHP will assign the keys by default.

Try this:

$votes = $row['votes_up']; 
$votes = $row['votes_down']; 

answered Sep 22, 2014 at 19:07

David's user avatar

DavidDavid

4292 gold badges5 silver badges14 bronze badges

In my case it was a simple type

$_SESSION['role' == 'ge']

I was missing the correct closing bracket

$_SESSION['role'] == 'ge'

answered Nov 23, 2018 at 7:44

Hammad Khan's user avatar

Hammad KhanHammad Khan

16k16 gold badges111 silver badges134 bronze badges

If you are using dompdf/dompdf and error occure in vendor/dompdf/dompdf/src/Cellmap.php then
It looks like we’re using the wrong frame id in the update_row_group method. Initial testing seems to confirm this. Though that may be because this is strictly a paged table issue and not too many of the documents in my test bed have paged tables.

Can you try changing line 800 to:

$r_rows = $this->_frames[$g_key][«rows»];
($g_key instead of $r_key)

https://github.com/dompdf/dompdf/issues/1295

answered Dec 19, 2018 at 7:51

Madhavi Khatal's user avatar

Use mysql row instead

mysql_fetch_row($r)

Meanwhile consider using mysqli or PDO

?>

Try seeding data with command: php artisan db:seed.

sssurii's user avatar

sssurii

7284 silver badges15 bronze badges

answered Jul 26, 2021 at 4:09

Nam Sama's user avatar

Nam SamaNam Sama

3253 silver badges5 bronze badges

0

its just a warning use:

error_reporting(0);

it shows when we do not initialize array and direct assigning value to indexes.

somefunction{
$raja[0]="this";
$raja[1]="that";
}

instead :

somefunction{
$raja=array(0=>'this',1='that');
//or
$raja=array("this","that");
}

it just notification, do not generate any output error or any unexpected output.

answered Aug 27, 2014 at 7:59

Teerath Kumar's user avatar

3

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save 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.

  • 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";
    }
    
    ?>

    The output will show:

      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";
    }
    
    ?>

    The output will look as follows:

     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));
    
    ?>

    The output will be:

     Key Found
    

    Понравилась статья? Поделить с друзьями:
  • Ошибка u3110 volkswagen
  • Ошибка unb на стиральной машине haier что это такое
  • Ошибка unb на стиральной машине haier что делать
  • Ошибка u3008 форд фокус 3
  • Ошибка unb на стиральной машине haier как исправить ошибку