Krisztian Toth
Krisztian Toth

Reputation: 63

How to store a zero in an array in php

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;

Upvotes: 0

Views: 788

Answers (2)

Denis METRAL
Denis METRAL

Reputation: 39

Better like this :

    $subjects_array = ["Selling", "Buying", "Services", "Other"];

    $requestdata = [
        'company' => 'some company',
        'country' => 'some country',
        'message' => 'some message',
        'link' => 'www.somelink.com',
        'containers' => 'some container',
        'products' => 'some product',
        'subject' => 0,
    ];

    $ncf_values = [];
    foreach ($requestdata as $key => $value) {
        $ncf_values[ "fieldValue" ] = [];
        $ncf_values[ "fieldValue" ][ "contact" ] = 120;
        $ncf_values[ "fieldValue" ][ "field" ] = 12;
        $ncf_values[ "fieldValue" ][ "value" ] = $key == 'subject' ? $subjects_array[ $requestdata[ $key ] ] : $requestdata[ $key ];
    }

Upvotes: -1

AbraCadaver
AbraCadaver

Reputation: 78994

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
}

Upvotes: 7

Related Questions