PHP – Add a default value to all the subarrays

Issue

I have an array that has some sub arrays. I need to add a default value to all of the sub arrays. I’ve tried some suggestions but none of the helped.

array(1) { ["ClassOne"]=> 
                { 
                [0]=>{ ["rollno"]=> "C1" ["dateofbirth"]=> "1974-06-07"} 
                [1]=>{ ["rollno"]=> "C2" ["dateofbirth"]=> "1970-01-01"} 
                }

            }

needs to changed to

array(1) { ["ClassOne"]=> 
                { 
                [0]=> { ["rollno"]=> "C1" ["dateofbirth"]=> "1974-06-07" ["defaultValue"]=> "someValue"} 
                [1]=> { ["rollno"]=> "C2" ["dateofbirth"]=> "1970-01-01" ["defaultValue"]=> "someValue"} 
                }

            }

Solution

Use foreach to get the index where you are going to append the “defaultvalue” Hope this answer is sufficient,thanks

/* your array as describred */

$array = array(
    array("ClassOne"=>
    array( "rollno"=> "C1","dateofbirth"=> "1974-06-07" ),
    array( "rollno"=> "C2","dateofbirth"=> "1970-01-01"),
    ),
    array("ClassTwo"=>
    array( "rollno"=> "C1","dateofbirth"=> "1974-06-07" ),
    array( "rollno"=> "C2","dateofbirth"=> "1970-01-01"),
    )

);

 foreach($array as $key=>$value)
  {
    foreach($array[$key] as $key1 => $value1)
    $array[$key][$key1]['defaultValue']='someValue';

  }

print_r($array);

Answered By – Deepak A

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published