Matthew Campbell
Matthew Campbell

Reputation: 1118

PHP/MySQL: list And explode Multiple Characters

This is something that I've mostly finished and I'm wondering if there's a way to clean up the code and to get to function correctly.

I have a table with the date and time a user joined (YYYY-MM-DD HH:MM:SS). I was wanting to split up the various values so I used both the list explode functions, but was only able to split one group of values:

$joined = $row ["joined"]; // <- "2008-06-03 15:01:08"
list ($year, $month, $day) = explode ("-", $joined);
list ($hour, $minute, $second) = explode (":", $joined);
list ($seperation) = explode (" ", $joined);
echo $joined . "<br>\n";
echo $year . "<br>\n";
echo $month . "<br>\n";
echo $day . "<br>\n";
echo $hour . "<br>\n";
echo $minute . "<br>\n";
echo $second . "<br>\n";

The following was the output:

2008-06-03 15:01:08 ($joined)
2008 ($year)
06 ($month)
03 15:01:08 ($day)
2008-06-03 15 ($hour)
01 ($minute)
08 ($second)

I'm wanting to know how I can explode the 3 characters (the dash, colon and space) to be able to use the variables correctly and have it look like the following:

2008-06-03 15:01:08 ($joined)
2008 ($year)
06 ($month)
03 ($day)
15 ($hour)
01 ($minute)
08 ($second)

Upvotes: 0

Views: 279

Answers (1)

mega6382
mega6382

Reputation: 9396

Try the following:

$year = date("Y", strtotime($joined));
$month = date("m", strtotime($joined));
$day = date("d", strtotime($joined));
$hour = date("H", strtotime($joined));
$minute = date("i", strtotime($joined));
$second = date("s", strtotime($joined));

Or a better solution:

$date = getdate(strtotime($joined));

When dealing with dates it is best to use date parsing instead of explode, or regex. The above uses strtotime() to convert the date string into Unix timestamp and then outputs them based on the date patterns.

And the second solution is much better as it returns an associative array of time fields.

But if you really do want to use list() and explode, here is a solution.

list($date, $time) = explode(" ", $joined);
list ($year, $month, $day) = explode ("-", $date);
list ($hour, $minute, $second) = explode (":", $time);

It separates date and time first, and then uses explode on them separately.

Upvotes: 2

Related Questions