Home > Mobile >  PHP add different key value to array without array_merge
PHP add different key value to array without array_merge

Time:06-30

I have an settings array with some fixed values, but I need to be able to add an extra key value thats variable

$settings = ['height' => 10, 'width' => 20, 'fit' => 'crop'];

return new Settings(
    ['detail' => array_merge($options, ['foo' => 'bar']), 'detail-l' => array_merge($options, ['foo2' => 'bar2'])],
    ['small' => array_merge($options, ['foo3' => 'bar2'])],
);

But I don't think this is the best way, I would preferably not use array functions

My expected result would be 2 arrays that look like this

[
    'detail' => ['height' => 10, 'width' => 20, 'fit' => 'crop', 'foo' => 'bar'],
    'detail-l' => ['height' => 10, 'width' => 20, 'fit' => 'crop', 'foo2' => 'bar2']
]

[
    'small' => ['height' => 10, 'width' => 20, 'fit' => 'crop', 'foo3' => 'bar3']
]

CodePudding user response:

Use splat operator:

$settings = ['height' => 10, 'width' => 20, 'fit' => 'crop'];

return new Settings(
    ['detail' => ['foo' => 'bar', ...$settings], 'detail-l' => ['foo2' => 'bar2', ...$settings]],
    ['small' => ['foo3' => 'bar2', ...$settings]],
);

CodePudding user response:

While I still believe that array_merge will do what you want with rather little overhead, here is a function you could use.

function pushToArray(array $data, string $key, $value)
{
    $data[$key] = $value;
    return $data;
}

It copies the array, adds the key/value combination and returns the copy.

  • Related