php - Incrementing an array's value is causing warnings in the log -


i trying create array holds count of each course offer based on location , instructor. here sample code

$coursecnt = array(); foreach($courselist $course){       $coursecnt[$course['location']][$course['instructor']] += 1 } 

this code creates array , displays bunch of warnings like:

unidentified index "orlando" locations, unidentified index "john smith" instructor

i have found if make = 1 instead of += 1 warnings go away of course makes every course location/instructor 1 not good.

my next though checking if exists, if doesn't, make 1 , if += 1. here example

if(isset($coursecnt[$course['location']][$course['instructor']]){      $coursecnt[$course['location']][$course['instructor']] += 1 }else{      $coursecnt[$course['location']][$course['instructor']] = 1 } 

this results in fatal error:

cannot use string offset array

$course array structure 2 dimensional array pulled sql

sample:

courseid   location   instructor 1          orlando    john smith 2          detroit    bill murray 

you not checking if location exists before checking instructor in first line of new version of code. need check if exists , create in $coursecnt array if doesn't (as empty array). after that, can check instructor:

// initialise empty array $coursecnt = array();  // create location if not in array if( ! isset($coursecnt[$course['location']])) {    $coursecnt[$course['location']] = array(); }  // either increment instructor or create initial value of 1 if ( isset($coursecnt[$course['location']][$coursecnt[$course['instructor']]]) ) {   $coursecnt[$course['location']][$coursecnt[$course['instructor']]] += 1; } else {   $coursecnt[$course['location']][$coursecnt[$course['instructor']]] = 1; } 

you've got lot of square brackets going on in there, might find easier read if use php's array_key_exists (documentation) instead of isset:

// initialise empty array $coursecnt = array();  // create location if not in array if( ! array_key_exists($course['location'], $coursecnt)) {    $coursecnt[$course['location']] = array(); }  // either increment instructor or create initial value of 1 if ( array_key_exists($course['instructor'], $coursecnt[$course['location']]) ) {   $coursecnt[$course['location']][$coursecnt[$course['instructor']]] += 1; } else {   $coursecnt[$course['location']][$coursecnt[$course['instructor']]] = 1; } 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -