While this should probably go without saying, I found myself in this situation recently. I spent a good half hour scratching my head, trying to figure out why the value was correct, but the name was completely wrong. Finally, I realized that two items shared the same value, so the first was being overwritten. I felt I should document the problem on here so that other developers may hopefully keep it in mind when developing dynamic arrays.
Take for example the following array in PHP:
$list = array( $item1 => 'Breakfast', $item2 => 'Lunch', $item3 => 'Dinner' );All is good assuming you eat different things for each meal. For example, if you have the following variables:
$item1 = "Cereal"; $item2 = "Salad"; $item3 = "Steak";Your array will look as such:
array (size=3) 'Cereal' => string 'Breakfast' (length=9) 'Salad' => string 'Lunch' (length=5) 'Steak' => string 'Dinner' (length=6)But what happens if you are on a budget that month, and have cereal for dinner, too?
$item1 = "Cereal"; $item2 = "Salad"; $item3 = "Cereal";You end up with:
array (size=2) 'Cereal' => string 'Dinner' (length=6) 'Salad' => string 'Lunch' (length=5)Uh oh. That's no good.
It's really best to not use dynamic keys, as much as possible. This array can easily be changed to the following without causing any significant changes in the way your code would need to access it.
$list = array( 'Breakfast' => $item1, 'Lunch' => $item2, 'Dinner' => $item3 );
No comments:
Post a Comment