Alex
Alex

Reputation: 9265

array flip collision issue

Is there a function/method I am unaware of that avoids removal of like keys when the array is flipped. Example below:

Original array:

Array ( [last_modified] => input [published] => input [project_content] => textarea ) 

With array flip (collision of keys):

Array ( [input] => published [textarea] => project_content )

Upvotes: 3

Views: 622

Answers (2)

Jon
Jon

Reputation: 437336

There is a dead simple way to get all the keys in the array that have the value "input" using the standard function array_keys:

$keys = array_keys($array, "input");

That is all; see it in action.

Upvotes: 1

jh314
jh314

Reputation: 27802

If you want to preserve your keys, you can have a two dimensional array:

<?php
$arr = array ( 'last_modified' => 'input', 'published' => 'input', 'project_content' => 'textarea' );
$result = array();
foreach($arr as $k => $v) {
    if (array_key_exists($v, $result)) {
        $result[$v][] = $k;
    } else {
        $result[$v] = array($k);        
    }
}
print_r($result);
?>

This will print out:

Array
(
    [input] => Array
        (
            [0] => last_modified
            [1] => published
        )

    [textarea] => Array
        (
            [0] => project_content
        )

)

Upvotes: 5

Related Questions