I recently upgraded to PHP 7.2 and i've been running some old legacy code for a stupid record keeping system. Basically it holds an array of contest_id's and the entries to each contest.
/*
@Use: Adds entries into the active contest for a given member.
@Param: $user_id - INT
@Param: $entries - INT
*/
function add_vip_entries($user_id, $entries) {
$user_data = get_user_meta( $user_id, 'all_contests', true );
$contest_id = get_active_contest();
if ($contest_id !== 0) {
if (isset($user_data['all_contests'][$contest_id]['entries'])) {
$user_data['all_contests'][$contest_id]['entries'] = intval($user_data['all_contests'][$contest_id]['entries'] + $entries);
} else {
$user_data['all_contests'][$contest_id]['entries'] = $entries;
}
update_user_meta( $user_id, 'all_contests', $user_data );
}
}
This used to work fine but now if it's the first time the user gain entries to a given contest I get the following error.
Uncaught exception 'Error' with message 'Cannot use string offset as an array'
And it triggers on this exact line:
$user_data['all_contests'][$contest_id]['entries'] = $entries;
How Can I replicate the behavior it had in PHP7.0? It used to simply push create the data structure or if it was a brand new contest push a new contest ID and set of entries. Now it errors. I tried to edit into this
$user_data = array('all_contests' => array($contest_id => array('entries' => $entries)));
But this causes an issue where if a new contest ID is introduced it will set the data structure to only contain the contest ID and entry pair being set.
$user_data['all_contests'][$contest_id]and$entriesbe?$user_datadoesn't contain an array. Maybe you just need to check the type and initializeall_contestsif it doesn't.$user_data['all_contests'][$contest_id]stores an integer, you cannot use a string offset to access its data, so using$user_data['all_contests'][$contest_id]['entries']is invalid.