developer tip

주의 : 정의되지 않은 오프셋 : 0 인치

copycodes 2021. 1. 7. 08:08
반응형

주의 : 정의되지 않은 오프셋 : 0 인치


이 PHP 오류가 발생합니다. 무슨 의미입니까?

Notice: Undefined offset: 0 in 
C:\xampp\htdocs\mywebsite\reddit_vote_tut\src\votes.php on line 41

이 코드에서 :

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

0값을 요청하고 $votes있습니다. 해당 키를 포함하지 않는 배열입니다.

배열 $votes이 설정되지 않았으므로 PHP가 0배열 의 키 액세스하려고 할 때 [0] 및 [1]에 대해 정의되지 않은 오프셋이 발생하고 오류가 발생합니다.

어레이가있는 경우 :

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

이제 다음 항목에 액세스 할 수 있습니다.

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

시도하고 액세스하는 경우 :

$votes[3];

"알림 : 정의되지 않은 오프셋 : 3"오류가 발생합니다.


이 답변이 도움이되었습니다. https://stackoverflow.com/a/18880670/1821607 호감의 이유 — 인덱스 0이 설정되지 않았습니다. 간단 $array = $array + array(null)합니다. 또는 인덱스 0의 배열 요소가를 통해 설정되었는지 확인해야합니다 isset($array[0]). 두 번째 변형은 저에게 가장 좋은 접근 방식입니다.


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.


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.


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

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

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.


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.


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.


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

Try this:

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

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.


In my case it was a simple type

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

I was missing the correct closing bracket

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

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


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.

ReferenceURL : https://stackoverflow.com/questions/6549561/notice-undefined-offset-0-in

반응형