Merge array only into empty values

Asked

Viewed 21 times

1

I have a function that takes as parameter an array, for example:

$args = array(
    "foo" => "value"
);
oneFunction( $args );

function oneFunction( $array ){
    $default = array(
        "foo" => "foo",
        "bar" => "bar"
    );
    //mescla valores
    $array = mesclaArrays($default, $array);

    //nesse exemplo, a saída deve ser
    //array(
    //  "foo" => "value",
    //  "bar" => "bar"
    //);
}

Is there a native function for this or is it necessary for me to create my own?

1 answer

1


You can do it backwards and insert it into $default what comes out with a loop.

function oneFunction( $array ){
    $default = array(
        "foo" => "foo",
        "bar" => "bar"
    );
    //mescla valores
    foreach ($array as $key => $value) $default[$key] = $value;
    return $default
}

That way you add new chave -> valor and/or modifications keys existing with the new value.

  • 1

    Shit, why didn’t I think of it before. It was so much simpler that I was curling up and creating a giant function. I adapted to my needs and gave it right. Thank you very much friend

Browser other questions tagged

You are not signed in. Login or sign up in order to post.