Ben
Ben

Reputation: 115

Merging Arrays and putting them into a a dd/mm/yyyy format

I have 3 arrays. One for date, one for month and one for year. I want to merge all the arrays so the values of the day, month and year arrays all have separate values in one array.

Example:

I want to turn:

Array
(
    [0] => 05
    [1] => 18
    [2] => 31
)
Array
(
    [0] => 04
    [1] => 11
    [2] => 12
)
Array
(
    [0] => 2013
    [1] => 1998
    [2] => 2006
)

into

Array
(
    [0] => 05/04/2013
    [1] => 18/11/1998
    [2] => 31/12/2006
)

I have looked at merging arrays or appending arrays but this doesn't seem to work. The reason I want them in the format dd/mm/yyyy is so then I have a date format when I put these dates into my mysql database.

Upvotes: 1

Views: 50

Answers (3)

Namitha
Namitha

Reputation: 204

<?php
$newArray = array();
$array1 = array(05,18,31);
$array2 = array(04,11,12);
$array3 = array(2013,1998,2006);

$i=0;
foreach($array1 as $value) {
    $newArray[] = $value.'/'.$array2[$i].'/'.$array3[$i];
    $i++;
}
  echo '<pre>';print_r($newArray);exit;
?>

Upvotes: 1

dhruv jadia
dhruv jadia

Reputation: 1680

Try using

$days = array(05, 18, 31);
$months = array(04, 11, 12);
$years = array(2013, 1998, 2006);

$result = array_map(
    function ($d, $m, $y) {
        return sprintf("%d/%d/%d", $d, $m, $y);
    },
    $days,
    $months,
    $years
);
echo "<pre>";
print_r($result);

Screenshot

enter image description here

Upvotes: 1

DonCallisto
DonCallisto

Reputation: 29912

Try with

$days = [5, 18, 31];
$months = [4, 11, 12];
$years = [2013, 1998, 2006];

$result = array_map(
    function ($d, $m, $y) {
        return sprintf("%s/%s/%s", $d, $m, $y);
        // return DateTime::createFromFormat('d/m/Y', sprintf("%s/%s/%s", $d, $m, $y)); <-- if you need a DateTime object
    },
    $days,
    $months,
    $years
);

Pay attention

[] is short array syntax introduced since php 5.4, if you're running on older version, use the canonical array()

Upvotes: 3

Related Questions