'Check if a value not exist in array
I want to make a day_off array based on work_day array, for example is if current date doesn't exist in work_day array for each group. I want to store it into new array.
I have work_day array like this (1 for sunday):
array (
0 =>
(object) array(
'group_id' => '854b5b57-f863-4e48-ba9b-617899c64750',
'day' => 2,
),
1 =>
(object) array(
'group_id' => '854b5b57-f863-4e48-ba9b-617899c64750',
'day' => 3,
),
2 =>
(object) array(
'group_id' => '854b5b57-f863-4e48-ba9b-617899c64750',
'day' => 4,
),
3 =>
(object) array(
'group_id' => 'f3f739d2-77fe-4e1f-b7fc-44242f52610b',
'day' => 5,
),
4 =>
(object) array(
'group_id' => 'f3f739d2-77fe-4e1f-b7fc-44242f52610b',
'day' => 6,
),
What I do next is to check if current day is exist or not inside work_day array for each group_id. If it's not exists, then I want to store the group_id and the date for today.
I've tried like this:
$day_off = array();
// Loop work day array
foreach ($work_day_arr as $key => $work_hour) {
// convert date now to numeric so I can compare it with the data from work_day array
$day_now = date('N', strtotime($date_now));
// If day from work_day array not equals to current day store it into day_off array.
// This is the right way to check if current day is exist?
if($work_day->day != $day_now + 1){
$data = (object) array();
$data->attendance_group_id = $work_hour->group_id;
$data->off_date = $date_now;
$day_off[] = $data;
}
}
The result format of day_off array is something like this (this is the result from code above, still wrong because it created duplicate data) :
array:65 [▼
0 => {#1610 ▼
+"attendance_group_id": "854b5b57-f863-4e48-ba9b-617899c64750"
+"off_date": "2022-04-14"
}
1 => {#1495 ▼
+"attendance_group_id": "854b5b57-f863-4e48-ba9b-617899c64750"
+"off_date": "2022-04-14"
}
2 => {#1477 ▼
+"attendance_group_id": "854b5b57-f863-4e48-ba9b-617899c64750"
+"off_date": "2022-04-14"
}
3 => {#1675 ▼
+"attendance_group_id": "854b5b57-f863-4e48-ba9b-617899c64750"
+"off_date": "2022-04-14"
}
4 => {#1676 ▼
+"attendance_group_id": "854b5b57-f863-4e48-ba9b-617899c64750"
+"off_date": "2022-04-14"
}
5 => {#1677 ▼
+"attendance_group_id": "854b5b57-f863-4e48-ba9b-617899c64750"
+"off_date": "2022-04-14"
}
6 => {#1678 ▼
+"attendance_group_id": "f3f739d2-77fe-4e1f-b7fc-44242f52610b"
+"off_date": "2022-04-14"
Solution 1:[1]
Try This for checking the current date is exists or not inside work_day array
in_array(date('d'),array_column($work_day, 'day'))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ajay |
