0

I have built an API that I want to test. By that reason I'm building a simple client to try out the different features (CRUD). Below is the function for updating a producer, which works fine. However, I also want to be able to update parts of a producer, e.g. address (/producers/8?method=put&address=milkyway).

The array producer always contains the same elements (name, address, zipcode etc) but I only want to update the producer with the elements in the array which contains of anything. What I mean with that is that if for example the name element in the array is empty then name shouldn't be included in *http_build_query*. If only the name element contains of anything then only name should be updated.

So, let's say that the array (except for id that of course is mandatory) contains of address. How can I dynamically add only that to *http_build_query* ?

Thanks in advance!

public function UpdateProducer($producer) {

    $url = 'http://localhost/webbteknik2/Labb2/api/v1/producers/ . $producer['id'] . '?method=put';

    $data = http_build_query(array(
        'name' => $producer['name'],
        'address' => $producer['address'],
        'zipcode' => $producer['zipcode'],
        'town' => $producer['town'],
        'url' => $producer['url'],
        'imgurl' => $producer['imgurl'],
        'latitude' => $producer['latitude'],
        'longitude' => $producer['longitude'],
    ));

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    ...
    the rest of the curl code
}

Note: I know this is bad coding in many ways, but as I said I only, asap want to be able to test the CRUD functionality through the client.

1 Answer 1

2

use array_filter to remove the empty elements....

$params = array(
    'name' => $producer['name'],
    'address' => $producer['address'],
    'zipcode' => $producer['zipcode'],
    'town' => $producer['town'],
    'url' => $producer['url'],
    'imgurl' => $producer['imgurl'],
    'latitude' => $producer['latitude'],
    'longitude' => $producer['longitude'],
);

$data = http_build_query(array_filter($params, 'is_null'));
Sign up to request clarification or add additional context in comments.

2 Comments

You should use is_null as the callback. Otherwise, you filter falsy values like string 0
Worked like a charm, thanks a lot for a fast and good answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.