Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notice: Undefined offset: 0 in

Tags:

html

php

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!";  }  ?> 
like image 458
louismoore18 Avatar asked Jul 01 '11 14:07

louismoore18


People also ask

How do you fix Undefined offset?

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.

How do I fix Undefined offset 0 in PHP?

You can do an isset() : if(isset($array[0])){ echo $array[0]; } else { //some error? }

What is the meaning of undefined offset?

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.

How define offset in PHP?

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.


1 Answers

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"

like image 133
YonoRan Avatar answered Oct 12 '22 22:10

YonoRan