82

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

Notice: Undefined offset: 0 in 
C:\xampp\htdocs\mywebsite\reddit_vote_tut\src\votes.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
  • 146,994
  • 96
  • 417
  • 335
louismoore18
  • 897
  • 1
  • 7
  • 7

15 Answers15

96

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
  • 20,682
  • 14
  • 97
  • 107
YonoRan
  • 1,718
  • 9
  • 7
  • I have no '$new_array' in the code. Do i need this added then? – louismoore18 Jul 01 '11 at 15:06
  • 5
    No, I was using this as an example of whats causing the problem in your code, I was just trying to recreate the problem as a way of explaining it to you. your problem is that the array values: $votes have not been defined. so you get an error(Notice) you have to make sure that the array is being populated properly, cause it doesn't seem to be. – YonoRan Jul 01 '11 at 15:09
  • what do i define then and how do i define? – louismoore18 Jul 01 '11 at 16:22
  • 2
    If you look at your function "getAllVotes" you will notice that only if the query finds a result does it populate the array, if it doesn't find a result it won't populate the array ($votes), so I'm assuming that your getting this result because your query isn't returning any results. – YonoRan Jul 01 '11 at 17:10
  • Why does an attempt to access `$new_array[3]` say that the undefined offset is `0`, instead of `3`? – Brian Kendig Nov 08 '17 at 16:48
  • The Question is about the PHP notice, not error. I've checked that, I've array full of elements, yet getting the undefined offset notice for even the first key. – Muhammad Mehran Khan Attari Sep 21 '20 at 07:31
15

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

if (isset($votes)) {
   // Do bad things to the votes array
}
Mostafa Norzade
  • 1,578
  • 5
  • 24
  • 40
Agg-rey Muhebwa
  • 313
  • 3
  • 9
9

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
  • 1
  • 1
Dmitrii Malyshev
  • 629
  • 9
  • 12
8

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
  • 146,994
  • 96
  • 417
  • 335
Giulio Prisco
  • 941
  • 9
  • 16
5

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.

2

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
  • 1,578
  • 5
  • 24
  • 40
Espanta
  • 1,080
  • 1
  • 17
  • 27
2

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.

Mihai
  • 82
  • 1
  • 6
1
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.

Anthony Rutledge
  • 6,980
  • 2
  • 39
  • 44
1

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.

VijayRana
  • 953
  • 1
  • 13
  • 38
0

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

Try this:

$votes = $row['votes_up']; 
$votes = $row['votes_down']; 
David
  • 429
  • 2
  • 5
  • 14
0

In my case it was a simple type

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

I was missing the correct closing bracket

$_SESSION['role'] == 'ge'
TheTechGuy
  • 16,560
  • 16
  • 115
  • 136
0

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

0

Use mysql row instead

mysql_fetch_row($r)

Meanwhile consider using mysqli or PDO

?>

0

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

sssurii
  • 750
  • 4
  • 17
Nam Sama
  • 375
  • 3
  • 6
-3

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.

Teerath Kumar
  • 488
  • 5
  • 15