0

I have a multidimensional array in this format

[0] => Array
    (
        [0] => Supplier
        [1] => Supplier Ref
    )

I basically need to offset every array with a new field at the beginning, so the outcome should be:

[0] => Array
    (
        [0] => New Field
        [1] => Supplier
        [2] => Supplier Ref
    )

If I can run a loop through each array using for/foreach then that would be great but I'm struggling to find a good method of doing this. Any ideas?

Thanks

2
  • array_unshift() array_unshift — Prepend one or more elements to the beginning of an array -> $array = array_unshift($array,'New Field'); Commented Sep 25, 2014 at 16:31
  • ^^^In context of your loop: foreach ($outer_array as &$inner_array) { array_unshift($inner_array, 'New Field'); } ...note the & reference... Commented Sep 25, 2014 at 16:36

2 Answers 2

2

I can think of three straightforward ways

  1. Use a simple foreach and array_unshift

    foreach($arr as &$item) {
      array_unshift($item, 'new field');
    }
    
  2. Use array_walk to apply array_unshift to each array item (will modify the existing array)

    array_walk($array, function(&$item) { array_unshift($item, 'new field'); });
    
  3. Use array_map and array_unshift (will return a new array – but the arrays inside the original array will be modified nevertheless)

    array_map(function(&$item) {
      array_unshift($item, 'new field'); return $item;
    }, $array);
    
Sign up to request clarification or add additional context in comments.

Comments

0

You can use array_unshift() to offset array within array php. It prepend one or more elements to the beginning of an array.

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.