How can I avoid this Undefined index notice?

General discussions related to php

Moderators: egami, macek, gesf

Post Reply
PHPPadawan
New php-forum User
New php-forum User
Posts: 7
Joined: Sun May 20, 2018 10:30 am

Wed Dec 12, 2018 2:10 pm

Hi everyone,

the line "$cards[$card_name] += $count;" keeps giving me a undefined index notice, how can i fix it?

thanks in advance for any help.

Code: Select all

$deck = "Octane Optimized, Alpha Serrated, Sculpted Aegis #2, Nautical Carrier, Saiph Starmaw, Nautical Carrier, Hurkol Bloodvessel, Myrmidon Remnant #2, Virklaw #2, Xertek Glassmaker";

$array = explode(',', $deck);

print("<pre>".print_r($array,true)."</pre>");

$cards = array();

foreach($array as $item) {
    if (preg_match('/#(\d+)/', $item, $matches))
        $count = $matches[1];
    else
        $count = 1;

    $card_name = trim(preg_replace('/ #\d+/', '', $item));
    $cards[$card_name] += $count;
}

print("<pre>".print_r($cards,true)."</pre>");

User avatar
hyper
php-forum Fan User
php-forum Fan User
Posts: 775
Joined: Mon Feb 22, 2016 5:52 pm

Wed Dec 12, 2018 2:38 pm

You haven't defined the variable before using it:

Code: Select all

print ('First attempt');
$array1['first'] += 5;
print ("<pre>".print_r($array1,true)."</pre>");

print ('<br>Second attempt');
$array2['second']  = 1;
$array2['second'] += 3;
print ("<pre>".print_r($array2,true)."</pre>");

PHPPadawan
New php-forum User
New php-forum User
Posts: 7
Joined: Sun May 20, 2018 10:30 am

Wed Dec 12, 2018 3:33 pm

hey, thanks for the response.

which variable? I think your example suggests $card_name, is that right?

PHPPadawan
New php-forum User
New php-forum User
Posts: 7
Joined: Sun May 20, 2018 10:30 am

Wed Dec 12, 2018 3:39 pm

sorry! I was being daft!

Code: Select all

		if (isset ($cards[$card_name])){
			$cards[$card_name] += $count;
		}else{
		$cards[$card_name] = $count;
		}

User avatar
hyper
php-forum Fan User
php-forum Fan User
Posts: 775
Joined: Mon Feb 22, 2016 5:52 pm

Wed Dec 12, 2018 5:05 pm

Yep, you got it.

A 'notice' is a polite way of getting you to change what you are doing or the way you are doing it, the parser can deal with it, but you may get results that you didn't expect.

Defining variables before using them is considered good practice.

Post Reply