ginerjm Posted March 15, 2017 Share Posted March 15, 2017 Thought I understood how this works but having a problem making it work. Here is my code: foreach($_SESSION['golf_entrants'] as &$row) { if ($row['id_code'] == $id) { $row['entry_name'] == $name; $updated = true; } } $row is a two element array that is created by a fetchall from a query that grabs them. If my argument ($id) matches the element for a given row I want to replace the row's name value with the new $name value. Nothing is being altered at all. Quote Link to comment https://forums.phpfreaks.com/topic/303458-foreach-by-reference/ Share on other sites More sharing options...
mac_gyver Posted March 15, 2017 Share Posted March 15, 2017 $row['entry_name'] == $name; ^^^ this is a comparison, not an assignment, so one would expect nothing to be altered. Quote Link to comment https://forums.phpfreaks.com/topic/303458-foreach-by-reference/#findComment-1544249 Share on other sites More sharing options...
requinix Posted March 15, 2017 Share Posted March 15, 2017 Advice: any time you do a foreach by-reference, unset the variable after the loop. Or don't use references at all. Otherwise you might accidentally use the variable later in your code and create some really unusual bugs. And please, indent your code. foreach($_SESSION['golf_entrants'] as &$row) { if ($row['id_code'] == $id) { $row['entry_name'] = $name; $updated = true; } } unset($row); 1 Quote Link to comment https://forums.phpfreaks.com/topic/303458-foreach-by-reference/#findComment-1544250 Share on other sites More sharing options...
ginerjm Posted March 15, 2017 Author Share Posted March 15, 2017 OMG! I was so wrapped up in the 'by reference' thing that I didn't see the obvious typo in front of me. Thanks for the quick response. Quote Link to comment https://forums.phpfreaks.com/topic/303458-foreach-by-reference/#findComment-1544252 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.