Reputation: 1754
I'm trying to simply add +1 to an array like this
$game['teamA']['goals']++;
But then it'll throw me an error about undefined index. And I guess that's because $game['teamA']['goals']
is not set before I am adding a value to it.
But isn't there a way to workaround this?
I could set the $game['teamA']['goals'] = 0
in start of simulation, but then I have to do that with freekicks, penalties, cards etc., AND do it for both teams. Isn't there another way of doing this?
Thanks in advance :)
Upvotes: 0
Views: 95
Reputation: 2531
write a wrapper function to set the values.
<?php
function increment(&$dict, $key1, $key2) {
if (!isset($dict, $key1))
$dict[$key1] = array();
if (!isset($dict[$key1], $key2))
$dict[$key1][$key2] = 1;
else
$dict[$key1][$key2] ++;
}
$game= array();
increment($game, "teamA", "goals");
var_dump( $game);
?>
It really depends on what you expect on the runtime; if these operations are called often, it would be better to create all array indices before doing anything else, like https://stackoverflow.com/a/12873359/1689451 suggested.
Upvotes: 1
Reputation: 6968
I'd suggest you go with a "proper initialisation", as you suggested. That would some code to your program but it's always better then on each update to check. Better do
$game = array( 'teamA' => array('goals' => 0,
'freekicks' => 0,
'penalties' => 0,
// etc ...
),
'teamB' => array('goals' => 0,
'freekicks' => 0,
'penalties' => 0,
// etc ...
)
);
instead of
if(isset($game['teamA']['goals']))
$game['teamA']['goals']++;
else
$game[teamA]['goals'] = 1;
There's nothing wrong to properly init your variables - all of them. It's even advisable to do so.
Upvotes: 2
Reputation: 1606
You should ALWAYS initialise variables before they are used. One way to do this would be:
$game = array('teamA' =>
array(
'goals' => 0,
'freekicks' => 0,
'penalties' => 0,
....
),
'teamB' =>
array(
'goals' => 0,
'freekicks' => 0,
'penalties' => 0,
...
)
);
Upvotes: 2
Reputation: 167182
You can do one thing. Before incrementing, check for existence of the array, if not, create one! As simple as that. You can use a built-in function called isset()
, which checks the existence of the variable.
(isset($game['teamA']['goals']) ? $game['teamA']['goals']++ : $game['teamA']['goals'] = 1;
if
condition:if (isset($game['teamA']['goals'])
$game['teamA']['goals']++;
else
$game['teamA']['goals'] = 1;
Upvotes: 0