简体   繁体   中英

Prepend a single key-value pair to an Array

if (!array_key_exists('ip', $value)) {
    array_unshift($value, ['ip' => ""]);
}

.. this appends a new array, but I just need a key-value pair, like so:

Array
(
    [ip] => 192.168.1.1
    [firstname] => John
    [lastname] => Appleseed
)

How about:

$value = array ('foo' => 'bar');
if (! array_key_exists('baz', $value)) {
    $value = array ('baz' => 'quux') + $value;
}
var_dump($value);

See it in action .

使用array_merge:

$value = array_merge( array('ip' => "..."), $value );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM