Lets say I have array something like this:
$game = Array
(
['round'] => Array
(
['match'] => Array
(
['player_2'] => Array
(
[name] => asddd
[id] => 1846845
[winner] => yes
)
['player_21'] => Array
(
[name] => ddd
[id] => 1848280
[winner] => no
)
)
)
)
And lets say in Node.js/Javascript I need to check if player_3 winner key value is yes. In PHP, you did something like this:
if( $game['round']['match'][player_3]['winner'] == 'yes'){
}
Because there is no player_3 it returns false in PHP, but if I did something similar in Javascript:
if( typeof game['round']['match'][player_3]['winner'] != 'undefined' && game['round']['match'][player_3]['winner'] == 'yes'){
}
I would get error: (node:15048) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined, because player_3 doesn't exist in array and you can't check key value of array, that doesn't exist.
You could do this in Javascript:
if(
typeof game['round'] != 'undefined' &&
typeof game['round']['match'] != 'undefined' &&
typeof game['round']['match']['player_3'] != 'undefined' &&
typeof game['round']['match']['player_3']['winner'] != 'undefined' &&
typeof game['round']['match']['player_3']['winner'] == 'yes'
){
var playerIsWinner = true;
}else{
var playerIsWinner = false;
}
You check each array inside array from top down and make sure that they exists. I don't know if it actually works, but even if it does, it seems bad and stupid way to check something. I mean look how simple it is in PHP, while in Javascript I have to check each array existence inside array. So is there better way checking value of array?