To clarify my question more:
This code:
$search="Joe";
for ($j=1; $j<=5; $j++){
if($key = array_search($search, array_column($test, "name"))) {
echo $test[$key]["name"].' exists in array at key '.$key.". Increasing qty.<br \>";
$test[$key]["qty"] = $test[$key]["qty"] + 1;
} else {
echo $search." is not in the array. Adding it!<br />";
$test[] = array("name"=>$search, "qty"=>"1");
}
}
for ($k=0; $k<count($test); $k++){
echo $test[$k]['name']." x".$test[$k]['qty']."<br />";
}
Results in this output:
Joe is not in the array. Adding it!
Joe is not in the array. Adding it!
Joe is not in the array. Adding it!
Joe is not in the array. Adding it!
Joe is not in the array. Adding it!
Joe x1
Joe x1
Joe x1
Joe x1
Joe x1
As you can see, even though Joe gets added to the array on the first pass, the array search doesn't find it during the next 4 loops. It just gets added 4 more times, instead of adding to the quantity of the existing entry.
Now, if I initialize the array with some bogus values like this:
$test[] = array("name"=>"Steve", "qty"=>"1"); // THIS IS THE ONLY LINE THAT IS DIFFERENT FROM THE PREVIOUS CODE.
$search="Joe";
for ($j=1; $j<=5; $j++){
if($key = array_search($search, array_column($test, "name"))) {
echo $test[$key]["name"].' exists in array at key '.$key.". Increasing qty.<br \>";
$test[$key]["qty"] = $test[$key]["qty"] + 1;
} else {
echo $search." is not in the array. Adding it!<br />";
$test[] = array("name"=>$search, "qty"=>"1");
}
}
for ($k=0; $k<count($test); $k++){
echo $test[$k]['name']." x".$test[$k]['qty']."<br />";
}
Now the code works as intended. Joe is added on the 1st pass, and is found on the next 4 loops.... and we get this output, as intended:
Joe is not in the array. Adding it!
Joe exists in array at key 1. Increasing qty.
Joe exists in array at key 1. Increasing qty.
Joe exists in array at key 1. Increasing qty.
Joe exists in array at key 1. Increasing qty.
Steve x1
Joe x5
I can't figure out why it works if I add initialize the array with the bogus Steve entry.