Undefined offset: 0

Greetings to everyone:

I am currently working through one PHP and MySQL book and there is a project that involves building some kind of a matchmaking app.

I am getting this error message as I look through the list of user ids with foreach() loop.


Notice: Undefined offset: 0 in C:\\Program Files\\Apache Software Foundation\\Apache2.2\\htdocs\\mymismatch.php on line 59

Notice: Undefined offset: 1 in C:\\Program Files\\Apache Software Foundation\\Apache2.2\\htdocs\\mymismatch.php on line 59

Notice: Undefined offset: 2 in C:\\Program Files\\Apache Software Foundation\\Apache2.2\\htdocs\\mymismatch.php on line 59

Here is the code that generates an error:


for ($i = 0; $i < count($user_responses); $i++)
{
	if (($user_responses[$i]['response']+ $mismatch_responses[$i]['response']) == 3)//line 59 is here
	{
		//we found a mismatch
		$temp_score += 1;
		array_push($temp_array, $user_responses[$i]['topic_name']);
	}
}

The problem has something to do with the if statement, but I don’t know where it is. The code works just fine and below all the “Notice:” statements I get the result that I expect to get.

If someone needs more code, just request and I will send.
Thanks for any help.
Alex.

My assumption is that user_response variable and hte mis_matchresponse variable are not the same. In this case your mismatch_response is empty.

If you wanted to do some ugly code rewrite your if statement this way


    if (($user_responses[$i]['response']+ isset($mismatch_responses[$i]['response']) ?$mismatch_responses[$i]['response'] : 0 ) == 3)//line 59 is here

Incase you hadn’t see the ?: operator before it’s the tertiary operator basically it’s an if else statement.

so if oyu have


if ($a) {
   $var = 15;
} else {
    $var = 25;
}

//can be rewritten
$var = $a ? 15 : 25;

Also on a side note you’re not using a foreach loop, you’re using a for loop.

Thank you all for your contribution. Assumption of some of you was correct. Mismatch_response array was empty for some of the users I was looping through. As a result, this array was not assigned and therefore the “Undefined offset” notice. I deleted the empty user and I no longer get that message. All that I need to do is to make sure user is not empty and only then add it to user id array and loop through them.

Again, thank you for your help.

do a print_r() of $user_responses and $mismatch_responses, and see if the indexes 0, 1 and 2 are there.

Before your for loop,


var_dump($mismatch_responses);

i’m guessing your $mismatch_responses isnt filled.