Reputation: 1276
I have a php array like below.
$array1 =Array
(
[date_stamp] => 31/01/2018
[over_time_policy_id] => 3
[over_time] => 04:00
[over_time_policy-2] => 02:00 //this
[schedule_working] => 00:00
[schedule_absence] => 00:00
[shedule_start_time] =>
[shedule_end_time] =>
[min_punch_time_stamp] => 8:00
[max_punch_time_stamp] => 20:00
[regular_time] => 01:00
[over_time_policy-3] => 02:00 //this
[worked_time] => 12:00
[actual_time] => 12:00
[actual_time_diff] => 00:00
[actual_time_diff_wage] => 0.00
[hourly_wage] => 47.1200
[paid_time] => 12:00
)
I want to get the result of below from the array indexes.
$result = Array (
[0]=>over_time_policy-2
[1]=>over_time_policy-3
);
I implemented the following code but not outputting anything.
$searchword = 'over_time_policy-';
foreach (preg_grep('/\b$searchword\b/i', $array1) as $key => $value) {
print_r($key);
}
Please help me on this.
Upvotes: 1
Views: 50
Reputation: 1276
I came up with a answer as below,
$searchword = 'over_time_policy-';
$matches = array();
foreach($array1 as $k=>$v) {
if(preg_match("/\b$searchword\b/i", $k)) {
$matches[] = $k;
}
}
print_r($matches);
I gave me the array like below
$matches= Array (
[0]=>over_time_policy-2
[1]=>over_time_policy-3
);
Upvotes: 1
Reputation: 54
This has a little edit on the answer
$word = 'over_time_policy-';
$output = [];
foreach (array_keys($array1) as $k) {
if (preg_match("/\b$word\b/i", $k)) {
$output[] = $k;
}
}
print_r($output);
Upvotes: 1
Reputation: 1966
This may helpful to you. (Get Array Keys (array_keys
) and then apply preg_match
on that)
$array1 = [
'date_stamp' => '31/01/2018',
'over_time_policy_id' => 3,
'over_time' => '04:00',
'over_time_policy-2' => '02:00', //this
'schedule_working' => '00:00',
'schedule_absence' => '00:00',
'shedule_start_time' => '',
'shedule_end_time' => '',
'min_punch_time_stamp' => '8:00',
'max_punch_time_stamp' => '20:00',
'regular_time' => '01:00',
'over_time_policy-3' => '02:00', //this
'worked_time' => '12:00',
'actual_time' => '12:00',
'actual_time_diff' => '00:00',
'actual_time_diff_wage' => '0.00',
'hourly_wage' => '47.1200',
'paid_time' => '12:00'
];
$searchword = 'over_time_policy-';
$output = [];
foreach (array_keys($array1) as $k) {
if (preg_match("/\b$searchword\b/i", $k)) {
$output[] = $k;
}
}
echo "<br>";
print_r($output);
output :-
Array ( [0] => over_time_policy-2 [1] => over_time_policy-3 )
Upvotes: 3
Reputation: 2365
You can do as :
$searchword = 'over_time_policy-';
$output = [];
foreach ($array1 as $key => $value) {
if (preg_match('/'.$searchword.'/i', $key)) {
$output[] = $key;
}
}
print_r($output);
Upvotes: 3