1

I would like to build $goal array from $initial only. Any ideas? Thank you

Edit : the question could be how to differentiate associative parts from sequential ones.

$intial=[
    "one",
    "two"=>"myTwo",
    "three",
    "four"=>"myFour"
];
$goal=[
    "one"=>null,
    "two"=>"myTwo",
    "three"=>null,
    "four"=>"myFour"
];
tit
  • 599
  • 3
  • 6
  • 25
  • they are both separate arrays ? ````foreach($goal as $key=>$val){ echo $key .' == '. $val . '
    '; }```` or just ````var_dump($goal);````
    – futureweb Apr 24 '18 at 23:41
  • Hi. I have only $initial array and I need to build $goal from it. – tit Apr 24 '18 at 23:44
  • you would have to check if the value exists or isset something like: ````$goal = []; foreach($initial as $key => $val){ if(isset($val){ $goal[$key] = $val }else{ $goal[$key] = $key; } }```` – futureweb Apr 24 '18 at 23:53
  • This is not working, outputing Array ( [0] => one [two] => myTwo [1] => three [four] => myFour ) – tit Apr 25 '18 at 00:01

2 Answers2

1

The 'sequential' parts will have numeric keys, so if your 'associative' keys will always be strings, you could use that to differentiate:

$goal = [];
foreach ($initial as $key => $value) {
    if (is_numeric($key)) {
        $goal[$value] = null;
    } else {
        $goal[$key] = $value;
    }
}
Tim Fountain
  • 33,093
  • 5
  • 41
  • 69
0
$goal = []; 
 foreach($initial as $key => $val){ 
   if(isset($val){ 
     $goal[$key] = $val; 
   }else{ 
      $goal[$key] = $key; 
   } 
  }  
futureweb
  • 442
  • 4
  • 12
  • This is not working, outputing Array ( [0] => one [two] => myTwo [1] => three [four] => myFour ) – tit Apr 25 '18 at 00:01