Page 1 of 1

array_map() not working as expected in game.php

Posted: 27 January 2023, 00:04
by IndianaScones
I have the following code: (it's meant for setupNewGame() but is currently in getAllDatas() so I can debug it)

Code: Select all

$asset_deck = self::getObjectListFromDb("SELECT card_location_arg, card_type_arg, card_id FROM cards_and_tokens WHERE card_location='asset_deck'");
$gear_assets = [];

function sortAssets($asset) {
    global $gear_assets;
    
    $gear_assets[] = [$asset['card_location_arg'], $asset['card_id']];
}

array_map('sortAssets', $asset_deck);
It's trimmed down here for clarity. For some reason, nothing gets added to $gear_assets. Nothing I do within array_map seems to make it to the global scope. I tested similar code on onlinephp.io here:
https://onlinephp.io?s=VZHbioMwEIavFXyH ... 2C&v=8.2.1
It worked as I expected in the above link, pushing new entries from within the callback function correctly added them to the global variable. For some reason though it's not working in game.php.

Re: array_map() not working as expected in game.php

Posted: 27 January 2023, 01:40
by SwHawk
You should check the PHP documentation about array_map() . It returns the modified array. It doesn't work in place. You should probably use array_walk if that's the behaviour you need... Or even array_filter looking at your example... Also, that's a personal note, but I tend to avoid using global scoped variables as much as possible...

Re: array_map() not working as expected in game.php

Posted: 27 January 2023, 06:34
by IndianaScones
SwHawk wrote: 27 January 2023, 01:40 You should check the PHP documentation about array_map() . It returns the modified array. It doesn't work in place. You should probably use array_walk if that's the behaviour you need... Or even array_filter looking at your example... Also, that's a personal note, but I tend to avoid using global scoped variables as much as possible...
Thanks, I realized it returns the modified array but I thought I could still use it to perform other operations that don't affect the original array. I will try array_filter(). Like I said, for some reason array_map() works in the onlinephp.io link I posted above.