NotionCommotion Posted December 12, 2018 Share Posted December 12, 2018 If getValue is given a path which doesn't exist, I can use the isset check to return null. I can also use the uncommitted $tmp =&$tmp[$key];. Why does this prevent an undefined index warning? public function getValue(string $path) { $path=explode('.', $path); $tmp=$this->config; foreach($path as $key) { //if(!isset($tmp[$key])) return null; //$tmp =$tmp[$key]; $tmp =&$tmp[$key]; } return $tmp; } 1 Quote Link to comment Share on other sites More sharing options...
kicken Posted December 12, 2018 Share Posted December 12, 2018 Asking for a reference is considered a writing context. If the variable doesn't exist, it is created with a NULL value. Since you're overwriting $tmp each time, you don't notice any issues. If you were not overwriting it you'd notice those keys being created as the loop progresses. I use this when trying to group results from a query easily. For example, say I had a query that returned students and their enrolled courses and wanted to end up with an array with the list of students, and their enrollments by session. I'd do something like: $result = []; foreach ($stmt as $row){ $studentId = $row['studentId']; $sessionId = $row['sessionId']; $courseId = $row['courseId']; $student = &$result[$studentId]; if (!$student){ //Haven't seen student yet $student = [ 'fistName' => $row['studentFirstname'] , 'lastName' => $row['studentLastname'] , 'id' => $studentId , 'sessionList' => [] ]; } $session = &$student['sessionList'][$sessionId]; if (!$session){ //Haven't seen session yet $session = [ 'name' => $row['sessionName'] , 'id' => $sessionId , 'courseList' => [] ]; } //Assume no course duplicates. $course = &$session['courseList'][$courseId]; $course = [ 'name' => $row['courseName'] , 'id' => $courseId ]; } The code is simpler due to not having to check if keys exist or not by using isset() in each step. Using the reference will create the key and I can do a simple if to see if it was newly created or already existed. It also make a nice alias so at the end I can just do $session['courseList'][$courseId] instead of having to do $result[$studentId]['sessionList'][$sessionId']['courseList'][$courseId]. 1 Quote Link to comment Share on other sites More sharing options...
NotionCommotion Posted December 12, 2018 Author Share Posted December 12, 2018 Ah, that makes sense! Thanks Quote Link to comment 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.