Skip to content
Advertisement

array_push(): Argument #1 ($array) must be of type array, string given [closed]

This is my code, and when I run this function I get this: array_push(): Argument #1 ($array) must be of type array, string given I trying to add value to the array

$data['status'] = 'success';
$data['msg'] = 'OK';
$aa = array();
if (!empty($countries)) {
    foreach ($countries as $row) {
        $b = $row['iso2'];
        $aa[$b] = array_push($row['name']);
    }
}
$data['result'] = $aa;

return setJSON($data);

this must be obtained:

{
    "status": "success",
    "msg": "OK",
    "result": {
        /*"iso2": "name",*/
        "DE": "Germany"
    }
}

Advertisement

Answer

array_push takes an array and a value to add to it. However the more common way would be just:

$aa[$row['iso2']] = $row['name'];

That being said, there is a built-in function so you don’t have to loop and do it:

$data['status'] = 'success';
$data['msg'] = 'OK';

if (!empty($countries)) {
    $data['result'] = array_column($countries, 'name', 'iso2');
}
return setJSON($data);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement