iwato Posted March 31, 2011 Share Posted March 31, 2011 Background: The following function is suppose to find duplicated values in an input array and return the corresponding elements grouped together in subarrays of an output array. The function fails when I try to turn add elements to a variable-variable array via the brackets operator. The following statement is rejected with the following error message:Statement: $$count_val[$key] = $val;Error Message: Uninitialized string offsetQuestion: How do you add elements to a variable-variable array? <?php function array_dupl_keys($array){ $count= array_flip(array_count_values($array)); if (array_key_exists(1, $count)) { foreach ($count as $key=>$val) { if ($key == 1) unset($count[$key]); } } $intersect = (array_intersect($array, $count)); foreach($count as $count_val) { $$count_val = array(); foreach($intersect as $key=>$val) { if ($count_val == $val) { $$count_val[$key] = $val; } } $summary[$count_val] = $$count_val; } return $summary; }?> Roddy Link to comment Share on other sites More sharing options...
iwato Posted March 31, 2011 Author Share Posted March 31, 2011 The following statement is rejected with the following error message:Statement: $$count_val[$key] = $val;Error Message: Uninitialized string offset Solution: I still do not understand the above error message, but with a little trial and error the following adjustment has proven successful, and the function performs as intended.${$count_val}[$key] = $val;Roddy Link to comment Share on other sites More sharing options...
iwato Posted March 31, 2011 Author Share Posted March 31, 2011 <?php function array_dupl_keys($array){ $count= array_flip(array_count_values($array)); if (array_key_exists(1, $count)) { foreach ($count as $key=>$val) { if ($key == 1) unset($count[$key]); } } $intersect = (array_intersect($array, $count)); foreach($count as $count_val) { $$count_val = array(); foreach($intersect as $key=>$val) { if ($count_val == $val) { ${$count_val}[$key] = $val; } } $summary[$count_val] = $$count_val; } return $summary; }?> For a, perhaps, obvious reason -- i.e. use of the array_flip() function -- the now ready array_dupl_keys() function only works with arrays containing values that can serve as valid keys. As such, arrays containing objects, subarrays, and the like, will fail.Roddy Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.