PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 15, 2022

[FIXED] How to append an index and values to an array dynamically with foreach PHP

 July 15, 2022     php, symfony, web-deployment     No comments   

Issue

I have this array and a value liken this...

'FirstBranch'

Array => (
     ['January'],
     ['February'],
     ['March']
)

And I need to create another array with the following structure...

['FirstBranch'] => array(
              ['January'] => array( 
                     'Value',
                     '%',
                     'Unit'
                    ),
              ['February'] => array(
                     'Value',
                     '%',
                     'Unit'
                    ),
              ['March'] => array(
                     'Value',
                     '%',
                     'Unit'
                    ),
             )

I tried to push the values through a foreach, but it doesn't work. The code I did looked like this...

foreach( $months as $month ){
    $resultArray['FirstBranch'] = array( 
                   $month => array('Value',
                                   '%',
                                   'Unit' 
                                )
                            );
}

When i do this, throws an error and it just doesn't work... Any ideas?


Solution

You can append your array using for each loop

<?php

 $array = array('January', 'February', 'March');

 $array2 = array('Value', '%', 'Unit');

 $newarray = array();
 foreach ($array as $key) {
   $newarray['FirstBranch'][$key] = $array2;
 }
 print_r($newarray);

Demo Here



Answered By - Muhammad Usman
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing