Reputation: 494
I'm trying to figure out if its possible to loop a foreach loop in a array, and the loop result should be as the keys of the new array, like this,
$names = array('joe', 'piter', 'jack');
$dates = array('06/22/1987', '05/25/1988', '08/26/1990');
$arr = array();
foreach($names as $v){
$arr[] = $v;
}
$arr2 = array($arr => $dates);
print_r($arr2);
How do I do that?
Thnaks guys.
Upvotes: 3
Views: 107
Reputation: 2734
Well, saw @ascii-lime's answer (which is much better) after I typed this up, but just as an alternative I guess...
$names = array('joe', 'piter', 'jack');
$dates = array('06/22/1987', '05/25/1988', '08/26/1990');
$arr = array();
$i=0;
foreach($names as $v){
$arr[$v] = $dates[$i];
++$i;
}
print_r($arr);
Upvotes: 2
Reputation: 141829
There is no need for a foreach loop to achieve that. Just use array_combine:
$names = array('joe', 'piter', 'jack');
$dates = array('06/22/1987', '05/25/1988', '08/26/1990');
$arr2 = array_combine($names, $dates);
print_r($arr2)
Outputs:
Array ( [joe] => 06/22/1987 [piter] => 05/25/1988 [jack] => 08/26/1990 )
In this situation you don't need to do this, but if you want to know how to use $v
as a key for $arr2
in your loop you can just do the assignment in your loop:
$arr2[$v] = ...;
Upvotes: 6