Gerald Mathabela
Gerald Mathabela

Reputation: 505

Foreach returns only 1 set of an array

i'm trying to create a method for an http request using this code, but it only picks up 1 set of key and value pair ("key_1"=>"value_1"). how do i get all the array keys and their values?

<?php
    $userPostData = [
        'key_1' => "value_1",
        'key_2' => "value_2"
    ];

  foreach($userPostData as $key => $value) {
    $response = $client->post($apiUrl, [
        'json' => [
             $key => urlencode($value),
        ],
        'verify' => false
        ]);
  }

Upvotes: 0

Views: 30

Answers (1)

Mihai Matei
Mihai Matei

Reputation: 24276

You can use array_map to urlencode the array values. Also, I think you forgot to encode the array to json, so I did it for you:

$userPostData = [
    'key_1' => "value_1",
    'key_2' => "value_2"
];

$userPostData = array_map('urlencode', $userPostData);

$response = $client->post($apiUrl, [
    'json'   => json_encode($userPostData), 
    'verify' => false
]);

Upvotes: 1

Related Questions