I am trying to store the value 0 in an associative array to later use it as a key to another array.
However I am not able to retrieve 0 with the code below.
What happens is that in the while loop they ‘subject’ key is completely ignored when the contents are 0.
Any other value is fine.
How can I loop over the associative array and get the 0 value?
And what is the reason for this behaviour?
$requestdata = []; $requestdata['company'] = 'some company'; $requestdata['country'] = 'some country'; $requestdata['message'] = 'some message'; $requestdata['link'] = 'www.somelink.com'; $requestdata['containers'] = 'some container'; $requestdata['products'] = 'some product'; $requestdata['subject'] = 0; while (current($requestdata)): $key = key($requestdata); if($key != "subject"): $ncf_values = []; $ncf_values["fieldValue"] = []; $ncf_values["fieldValue"]["contact"] = 120; $ncf_values["fieldValue"]["field"] = 12; $ncf_values["fieldValue"]["value"] = $requestdata[$key]; elseif($key == "subject"): $subjects_array = ["Selling","Buying", "Services", "Other"]; $ncf_values = []; $ncf_values["fieldValue"] = []; $ncf_values["fieldValue"]["contact"] = 120; $ncf_values["fieldValue"]["field"] = 12; $ncf_values["fieldValue"]["value"] = $subjects_array[$requestdata[$key]]; endif; next($requestdata); endwhile;
Advertisement
Answer
Because 0
evaluates loosely to false
and the while
terminates. Test explicitly:
while (current($requestdata) !== false):
However, why are you not using a foreach
?
foreach($requestdata as $key => $val) { // use $key and $val }