array_map() not working as expected in game.php

Game development with Board Game Arena Studio
Post Reply
User avatar
IndianaScones
Posts: 19
Joined: 07 June 2012, 07:04

array_map() not working as expected in game.php

Post 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.
User avatar
SwHawk
Posts: 133
Joined: 23 August 2015, 16:45

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

Post 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...
User avatar
IndianaScones
Posts: 19
Joined: 07 June 2012, 07:04

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

Post 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.
Post Reply

Return to “Developers”