user1085024
user1085024

Reputation: 21

How to get set of keys having same value from array in php

I want to know all keys whose values are same.

I have below array:

[monday] => 10:00 - 11:00, 
[tuesday] => 11:00 - 12:00,
[wednesday] => 10:00 - 11:00,
[friday] => 10:00 - 11:00,
[saturday] => 11:00 - 12:00,
[sunday] => 14:00 - 15:00,

monday/wednesday/friday = 10:00 - 11:00.

tuesday/saturday = 11:00 - 12:00.

sunday = 14:00 - 15:00.

Please help me.

Thanks in advance.

Upvotes: 0

Views: 462

Answers (1)

Peon
Peon

Reputation: 8020

You can do a simple foreach loop and join a new array depending on values:

<?php

$worktimes = array(
    'monday' => '10:00 - 11:00', 
    'tuesday' => '11:00 - 12:00',
    'wednesday' => '10:00 - 11:00',
    'friday' => '10:00 - 11:00',
    'saturday' => '11:00 - 12:00',
    'sunday' => '14:00 - 15:00'
);

$combined = array();
foreach ( $worktimes as $key => $value ) {
    $combined[$value][] = $key;
}

print_r( $combined );

?>

Now you have a new array that holds you key with all the values that match it.

Upvotes: 4

Related Questions