Compare two array using laravel - php

Hi everyone I have an array
$dates = [2016-11-02,2016-11-05,2016-11-11,2016-11-15,2016-11-16]
in this I am getting all dates now I want to compare with $currentdate (2016-12-16) like this
if($dates <= $currentdate){
echo "true";
} else{
echo "false";
}
Any help will be much appreciated.

Not sure about other answers, but if you are trying to validate all the dates, please use the below code... Should work :)
$isLess = false;
$currentDate = Carbon::now();
foreach($dates as $data) {
if(Carbon::parse($date)->lte(currentDate)){
$isLess = true;
break;
}
}
echo $isLess;
Let me know in the comments if you face any problem :)

you can parse it to Carbon and use its comparison function
$date = Carbon::parse($date);
if($date->lte(Carbon::today())){
// your code
}
Here
lte() means less than equal to
to know more about Comparison operator of carbon visit http://carbon.nesbot.com/docs/#api-comparison

Since you're using Laravel, you can do that with Carbon:
if (Carbon::now()->gte(Carbon::parse($oneDate))

In one line (albeit not the prettiest)
if (collect(collect($dates)->filter(function($date) use($currentDate) { return Carbon::parse($date)->lte($currentDate); }))->count > 0) {
}

Related

How to remove values from an array in Laravel

I am trying to make a really basic day booking system and need to return all dates within a range, and then remove selected dates from that range. I tried the following code but realised that will remove duplicates which is fine, but I also need that date to be removed too.
Can anyone suggest a good way of doing this?
In the below example I am just hoping to see:
2022-04-03T00:00:00.000000Z
2022-04-04T00:00:00.000000Z
2022-04-05T00:00:00.000000Z
$start_date = "2022-04-01";
$end_date = "2022-04-05";
$datesToRemove = [
'2022-04-01T00:00:00.000000Z',
'2022-04-02T00:00:00.000000Z'
];
$range = Carbon::parse($start_date)->toPeriod($end_date)->toArray();
$available = array_unique(array_merge($range, $datesToRemove));
return $available;
To compare it is necessary to have the compared values in the same format. I decide to morph the $datesToRemove to Carbon format. The you can use to nested loops and check with PHP in_array() function.
$start_date = "2022-04-01";
$end_date = "2022-04-05";
$datesToRemove = [
"2022-04-01T00:00:00.000000Z",
"2022-04-02T00:00:00.000000Z"
];
$range = \Carbon\Carbon::parse($start_date)->toPeriod($end_date)->toArray();
$datesToRemove2 = [];
foreach($datesToRemove as $r) {
$datesToRemove2[] = \Carbon\Carbon::parse($r);
}
$res = [];
foreach($datesToRemove2 as $index => $d1) {
if(in_array($d1, $range)) {
unset($range[$index]);
}
}
return $range;
output
{
"2":"2022-04-03T00:00:00.000000Z",
"3":"2022-04-04T00:00:00.000000Z",
"4":"2022-04-05T00:00:00.000000Z"
}
Means that

How to convert array to string in laravel

$date = gc_head::select('DATE','point_no')->orderBy('DOCDATE','desc')->limit(7)->get();
This return something like array format
[{"DATE":"2021-06-11 00:00:00","point_no":"SRT-358"},{"DATE":"2021-06-11 00:00:00","point_no":"SRT-359"},{"DATE":"2021-06-11 00:00:00","point_no":"SRT-360"},{"DATE":"2021-06-10 00:00:00","point_no":"SRT-357"},{"DATE":"2021-06-10 00:00:00","point_no":"SRT-356"},{"DATE":"2021-06-10 00:00:00","point_no":"SRT-355"},{"DATE":"2021-06-09 00:00:00","point_no":"SRT-348"}]
I want to isolate DATE and point_no. For example
$year=['2015','2016','2017','2018','2019','2020'];
I tried $date['DOCDATE'] to isolate date it's not working. Is there any better way to fix this??
$date = gc_head::select('DATE','point_no')->orderBy('DOCDATE','desc')->limit(7)->get();
$date_array = array();
foreach($date as $dat){
array_push($date_array, \Carbon\Carbon::parse($dat["DATE"])->format('Y');
}
return $date_array;
You can use array_map function.
$extractYear = function($date) {
return substr($date["DATE"], 0, 4);
};
$years = array_map($extractYear, $date);
try this query -
$years= gc_head::select('DATE','point_no')->orderBy('DOCDATE','desc')->limit(7)->get()->map(function ($q) {
return [Carbon::parse($q->DATE)->format('Y')];
});

Php filter multidimensional array

I have array like this:
arr=[
627=[
'lead_data'=>['name'=>'Name1', 'date'=>'2019-04-09']
],
500=[
'lead_data'=>['name'=>'Name2', 'date'=>'2018-05-07']
],
534=[
'lead_data'=>['name'=>'Name3', 'date'=>'2019-07-10']
],
100=[
'lead_data'=>['name'=>'Name4', 'date'=>'2019-05-12']
],
]
How can I filter this array where date is between 2019-05-01 and 2019-07-12.
So in result there will be elements with ids 534 and 100.
Or date is >= 2019-07-05 or date is <= 2019-01-01 ?
I know there is array_filter function, but cant understand how to use it in thus case? Please help, thanks
The simplest solution would to just iterate over your data like so:
<?php
$begin = date('Y-m-d', strtotime("2019-05-01"));
$end = date('Y-m-d', strtotime("2019-07-12"));
foreach($array as $key => $data)
{
$date = date('Y-m-d', strtotime($$data['date']));
if (($$data > $begin) && ($date < $end)){
unset($array[$key]);
}
}
var_dump($array);
Always make sure you check out official documentation on php.net because it usually have tons of examples and very thorough explanations.
In your case you can compare dates as strings (since they are in Y-m-d format and comparing them alphabetically will do the trick):
$filtered = array_filter($arr, function ($item) {
return ($item['lead_data']['date'] > '2019-05-01') && ($item['lead_data']['date'] < '2019-07-12');
});
By using array_filter(), and using the use keyword, you can supply variables into the filter - this can be the start- and end-dates for your limits.
When using array_filter(), the data will remain in the array if the return value inside the callback is true, otherwise it will be removed. So then compare the dates, and see if they are greater than $from, and less than $to.
$from = '2019-05-01';
$to = '2019-07-12';
$result = array_filter($arr, function ($v) use ($from, $to) {
return $v['lead_data']['date'] > $from && $v['lead_data']['date'] < $to;
});
print_r($result);
Live demo at https://3v4l.org/Cmt8H

how to check php variable has datetime value?

I have a php variable which contain date-time value like 2014-05-11 23:10:11 some times this may change, so i have to find it either it has date-time value or not, below is my variable
$my-variable='2014-08-26 18:25:47';
DateTime is a class in PHP. You should ask a different question if you want to validate a string. To validate a DateTime instance:
$my_variable instanceof DateTime
This should work for you to check if the string is a valid date time in your format:
<?php
$date = '2014-08-26 18:25:47';
function isTime($time) {
if (preg_match("/^([1-2][0-3]|[01]?[1-9]):([0-5]?[0-9]):([0-5]?[0-9])$/", $time))
return true;
return false;
}
$parts = explode(" ", $date);
list($y, $m, $d) = explode("-", $parts[0]);
if(checkdate($m, $d, $y) && isTime($parts[1]) ){
echo "OK";
} else {
echo "BAD";
}
?>
output:
OK
$my_variable='2014-08-26 18:25:47';
...
if ($my_variable instanceof DateTime) {
...
}
or
if (is_a($my_variable, 'DateTime')) {
...
}
If it's a string representing a date in time, you can use date_parse: http://php.net/manual/en/function.date-parse.php That will return an associative array with the parts of the date and time string if valid, FALSE if not.
If it's a date-time object, see the answer describing instanceOf.

Reverse date order in script

I have a recruitment script written in PHP that I am working with at present. On our registrations page there is a drop down for date of birth which you can see in action here:
http://www.v3recruitment.com/users/register.php
As you can see, the date starts at 1900, what I would like to do is reverse the date order. I think I have found the code thats generating the dates, but my PHP is not good enough to work out how to get it to show dates in a reverse order, here is that code:
function FetchYears($type){
$start = 1901;
$end = date("Y");
for($i=$start;$i<=$end;$i++){
$array[]['year'] = $i;
}
return $array;
}
The front end is using Smarty Templates and here is that code:
{section name="c" loop=$dob_years}
<option value="{$dob_years[c].year}" {get_value field=select selectvalue=$dob_years[c].year fieldname="dob_year"}>{$dob_years[c].year}</option>
{/section}
Can anyone please help me with this?
Either reverse loop or use array_reverse()
change return$array; to return array_reverse($array);
For smarty it's very simple you don't have to even create this function in PHP it can be done in smarty as well.
{foreach $dob_years as $entry)
<option value="{$entry.year}">{$entry.year}</option>
{/foreach}
Check HTML_SELECT_DATE in smarty or simply use just the code below doesn't require any additional php code.
{assign var=currentYear value=$smarty.now|date_format:"%Y"}
{assign var=fromYear value="2003"}
{section name=years start=$currentYear step=-1 loop=$fromYear}
{$smarty.section.years.index}
{/section
array_reverse does what it says on the tin.
Try like this
function FetchYears($type){
$start = date("Y");
$end = 1901;
for($i=$start;$i>=$end;$i--){
$array[]['year'] = $i;
}
return $array;
}
or simply use array_reverse while returning your array like
function FetchYears($type){
$start = 1901;
$end = date("Y");
for($i=$start;$i<=$end;$i++){
$array[]['year'] = $i;
}
return array_reverse($array);
}
function FetchYears($type){
$start = date("Y");
$end = 1901;
for($i=$start;$i>=$end;$i--){
$array[]['year'] = $i;
}
return $array;
}
for ($i = $end; $i >= $start; $i--) {
$array[]['year'] = $i;
}
Haven't tested it yet, should work :)
Probably the easiest way to do this would be to put the dates in UTC (integer) format.
$dates[$i] = $timestamp;
Then use the PHP sort function to sort the dates.
sort($dates,SORT_NUMERIC);
You can use rsort for the opposite.
rsort($dates,SORT_NUMERIC);
When you are finished, iterate through your array and covert back using the date() function.
echo (date('m-d-Y', $dates[$i]));

Categories