PHP average time from an array - php

How do I work out the average time from an array of times.
I have an array that looks like this :
('17:29:53','16:00:32')
And I wish to achieve the result 16:45:12 using PHP.

date('H:i:s', array_sum(array_map('strtotime', $array)) / count($array))
Untested solution typed on my phone, should work though.

$times = array('17:29:53','16:00:32');
$totaltime = '';
foreach($times as $time){
$timestamp = strtotime($time);
$totaltime += $timestamp;
}
$average_time = ($totaltime/count($times));
echo date('H:i:s',$average_time);

convert both using strtotime() function
add the value
divide by 2 (or how many items there in your array)
convert back to normal time format

Loop over all Entries and add times, converted to seconds
Divide by length of Array and convert back to hh:mm:ss

Related

Finding the average date given an array of PHP DateTime Objects

I have an array of PHP DateTime objects:
$dates = [
new DateTime('2019-08-15'),
new DateTime('2019-08-19'),
new DateTime('2019-08-20')
];
What I would like to receive from this array is the average date, which in my calculation would be 2019-08-18.
Is there a simple way of doing this without breaking down the date parts for each item and finding the average of all of them and then splicing it back together?
Thank you!
Basically you have no choice other than to iterate over all the values and summing them (using timestamps is the most efficient way), taking the average and then converting that value back to a date:
echo date('Y-m-d', array_reduce($dates, function ($c, $d) {
return $c + $d->format('U');
}, 0) / count($dates));
An alternate way would be to find the difference between each of the dates and the first date in the array, and then take the average of those values and add it to the first date:
$days = 0;
foreach ($dates as $date) {
$days += $dates[0]->diff($date)->days;
}
$days = intdiv($days, count($dates));
$avg_date = (clone $dates[0])->modify("+$days days");
echo $avg_date->format('Y-m-d');
In both cases the output is:
2019-08-18
Demo on 3v4l.org

php array consist of time values calculate average of it [duplicate]

How do I work out the average time from an array of times.
I have an array that looks like this :
('17:29:53','16:00:32')
And I wish to achieve the result 16:45:12 using PHP.
date('H:i:s', array_sum(array_map('strtotime', $array)) / count($array))
Untested solution typed on my phone, should work though.
$times = array('17:29:53','16:00:32');
$totaltime = '';
foreach($times as $time){
$timestamp = strtotime($time);
$totaltime += $timestamp;
}
$average_time = ($totaltime/count($times));
echo date('H:i:s',$average_time);
convert both using strtotime() function
add the value
divide by 2 (or how many items there in your array)
convert back to normal time format
Loop over all Entries and add times, converted to seconds
Divide by length of Array and convert back to hh:mm:ss

Filter PHP Array Keys and calculating mean value

I have an array with dates as keys and prices as values. Like this:
Array
(
[2016-11-11] => 25.05
[2016-11-12] => 25.05
[2016-11-13] => 25.05
[2016-11-14] => 25.05
...
)
Now i need to calculate the mean value of today - 1 till today - 8. Of course it should also calculating correctly if there is less than 8 entries.
I'm thinking of extracting the keys and filter for the values and put that all in for loop. But i bet there will be a better way. I am at least happy for an idea in which direction to start with. May you help me?
The "today" i defined like this:
date_default_timezone_set("Europe/Berlin");
$timestamp = time();
$today = date("Y-m-d",$timestamp);
edit:
The output should be like
$last_week_mean = "value" of key[today-1] + "value" of key [today-2]
+ ... / count(amount of key values in this range)
But i don't know how to build this query/filter - thing :)
You can use array_filter with ARRAY_FILTER_USE_KEY to get the specific date range you want. But after than, you don't need to use a loop to calculate the average. You can just use sum / count of the filtered array.
$d1 = date('Y-m-d', strtotime('8 days ago'));
$d2 = date('Y-m-d', strtotime('1 day ago'));
$range = array_filter($your_array, function($date_string) use ($d1, $d2) {
return $date_string >= $d1 && $date_string <= $d2;
}, ARRAY_FILTER_USE_KEY);
$average = array_sum($range) / count($range);
Also, just in case you're getting your initial array from a database, it would most likely be easier and more efficient to only select the dates you want to begin with.

converting H:i:s to minutes only but array_map() giving errors

I am trying to convert a long datatype data to time in which I am successful.
In each session time array I have values like ["1276999","787878","677267"]. I passed this array in the array_map function and converted to time which is working.
Now within the the convert_time function I am calling another function, using array_map which will convert each time (i.e 1:40:00 to 100 minutes) but the issue is my 2nd array map function which is giving me error that array_map needs 2nd parameter to be an array...
$each_session_time = array();
for ($i=0; $i<sizeof($array_in_time_str) ; $i++) {
$each_session_time[$i]=$array_out_time_str[$i]-$array_in_time_str[$i];
}
//session time in hours
array_map("convert_to_time", $each_session_time);
function convert_to_time($each_session) {
# code...
$each_sess_time=array();
$each_sess_time=date("H:i:s",$each_session);
array_map("get_minutes",$each_sess_time);
return $each_sess_time;
}
function get_minutes($session_time) {
// algorithm to convert each session time to minutes)
}
You need to move out the array_map("get_minutes",$each_session_time); from the convert_to_time function.
example:
<?php
$each_session_time=["1276999","787878","677267"];
//session time in hours
$times = array_map("convert_to_time", $each_session_time);
$minutes = array_map("get_minutes",$times);
function convert_to_time($each_session)
{
# code...
$each_sess_time=array();
$each_sess_time=date("H:i:s",$each_session);
return $each_sess_time;
}
function get_minutes($session_time)
{
//algo to convert each session time to minutes)
}
print_r($minutes);
It seems you are starting with valid timestamps - seconds passed since January 1, 1970 - so to get the difference between two values in minutes, you just have to subtract one from the other and multiply it by 60.
If you want more control over your data, for example to format it differently later on, I would recommend using DateInterval objects instead of the difference between two timestamps and strings that you are using now. Note that the difference between two timestamps is not a valid timestamp itself so you cannot use date() to format it.
considering you are working with strings like "XX:YY:ZZ" you can try
$split = explode(":",$session_time); $minutes = $split[1];
to get the "i" part of the string.
You could also use a dateTime object (http://php.net/manual/en/class.datetime.php) by doing new DateTime($each_session); in the first loop and using DateTime::format("H:i:s") and DateTime::format("i") on that object depending on what data you need

PHP shortcut to find smallest number / date

I have a situation whereby a series of 15 dates have been created, currently in UNIX timestamps.
Another variable <?php $dateidate = date(strtotime('+20 days')); ?>
The objective is to find the smallest of the 15 other dates that is greater > than $dateidate and display in the format of 'd-m-Y'
Once we've done that is there a way to get the second smallest of the 15 other dates that is greater > than $dateidate and display in the format of 'd-m-Y'.
So, you have 15 dates which are UNIX timestamps. Useful.
Ok, here's what you can do to do it easily:
$datearray = array(timestamp1,timestamp2,etc.) // an array of timestamps
$dateidate = time() + 1728000; //current time + 20 days worth of seconds (20 * 24 * 60 * 60)
foreach($datearray as $key => $date)
{
if($date < $dateidate)
{
unset $datearray[$key]; //Remove timestamp from original array if less than $dateidate
}
}
$earliestdate = min($datearray);
//min returns the least of the values in the array, opposite of max, which you could use to find the latest date in the array
$date = date('d-m-Y',$earliestdate);
strtotime generates a timestamp.
instead of this:
<?php $dateidate = date(strtotime('+20 days')); ?>
do this:
<?php $dateidate = strtotime('+20 days'); ?>
Put all timestamps into an array with special keys so you can distinguish which one is your pivot.
Sort that array and do what you need to do with the sorted array.
This solution filters the $dates array which stores the timestamps using an anonymous function, so in the $shorterOnes array you will have all the timestamps that are bigger than $dateidate.
Then the array is sorted, the first one will be smallest and so on.
$dateidate=strtotime('+20 days');
$dates=array(/*timestamps*/);
$shorterOnes=array_filter($dates, function ($v) use ($dateidate) {
return $v>$dateidate;
});
sort($shorterOnes);
echo date('d-m-Y', $shorterOnes[0]);
echo date('d-m-Y', $shorterOnes[1]);
Anonymous functions only work from PHP 5.3. Lower than that, you need to use create_function().

Categories