Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put foreach loop result as an key php

Tags:

arrays

php

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.

like image 588
thegrede Avatar asked Sep 05 '26 14:09

thegrede


2 Answers

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] = ...;
like image 124
Paul Avatar answered Sep 07 '26 02:09

Paul


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);
like image 24
hannebaumsaway Avatar answered Sep 07 '26 04:09

hannebaumsaway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!