0

I have an array of values, for example

$fred = Array('one','two','@group','three','four');

and a second array

$group = Array('alpha','beta','gamma');

Which is the most efficient way to substitute the value '@group' with the values inside $group array? That is, to obtain

$expanded_fred = Array('one','two','alpha','beta','gamma','three','four');

PS The grouping method has only one level. No nested groups.

2 Answers 2

2

First lets use array_search to find the key of the @group element:

$replaceKey = array_search('@group', $fred);

Next we'll use array_splice to replace the @group element with the $group array:

array_splice($fred, $replaceKey, 1, $group);

$fred is now your expanded array.

Demo here: https://3v4l.org/qf4ts

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

1 Comment

There may be more @group in $fred.
2

You can iterate the $fred to find all @group to replace them with $group. Demo

$result = [];
$fred = Array('one','two','@group','three','four');
$group = Array('alpha','beta','gamma');
foreach($fred as $value){
    if($value == '@group'){
        $result = array_merge($result,$group);
    }else{
        $result[] = $value;
    }
}
print_r($result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.