0

Coming from a javascript background, I'm having a little difficulty inserting a php array into another array.

If I have the following:

$common_properties = array(
    'foo' => 'bar',
    'eats' => array(
        'apples' => true,
        'oranges' => true
    )
);

$one = array(
    'name' => 'one',
    'desc' => 'Lorem'
);

$two = array(
    'name' => 'two',
    'desc' => 'Ipsum'
);

How can I make the $common_properties array accessible from $one and $two? I need to pass the resulting array(s) as arguments to a function. For some reason, array_merge resulted in an error.

The desired result should be, for example:

$one = array(
    'name' => 'one',
    'desc' => 'Lorem'
    'foo' => 'bar',
    'eats' => array(
        'apples' => true,
        'oranges' => true
    )
);
3
  • Can you be more explicit on what is your final desired result? What did you try and what was your error? Commented Oct 6, 2014 at 8:16
  • @MihaiIorga - yes, my bad - please see amendment for the desired result. Commented Oct 6, 2014 at 8:32
  • what do you mean array_merge() resulted into an error, i think you can just straight up merge them using that function Commented Oct 6, 2014 at 8:41

2 Answers 2

2
$one = array_merge($one, $common_properties);

print_r($one);
/* ⇨
Array
(
    [name] => one
    [desc] => Lorem
    [foo] => bar
    [eats] => Array
        (
            [apples] => 1
            [oranges] => 1
        )

)
*/
Sign up to request clarification or add additional context in comments.

1 Comment

Ah - I'd previously attempted to pass the entire array_merge function as the argument. php really isn't quite as forgiving as javascript.
2

You can do the below to add $common_properties to $one and $two

$one['commonProperties'] = $common_properties;

$two['commonProperties'] = $common_properties;

You can then pass the two arrays ($one and $two) to your method like so function_name($one, $two)

2 Comments

Also worth mentioning is that if you need to change array properties in $common_properties and have them reflect globally then you might want to assign by reference. Assign by value is fine for read-only or cases where it doesn't matter if $one and $two have different values, but if the state needs to remain in sync than =& is a better choice than =
Thanks - but unfortunately this doesn't yield the desired result. Please see the edit with the output I need.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.