Hello. There is an array

[cart] => Array ( [32] => 31 [29] => 31 [30] => 31 [22] => 5 [20] => 5 ) 

how to compare the value in this array, and if they are equal then add their keys to one line. For example: the key value 32 coincides with the value 29 and 30, you need to take these keys (32,29,30) and add srt_30 = (32,29,30) to the line. Can this be done at all?

Transferred from meta.ru.stackoverflow.com on Dec 3 '16 at 11:23 .

This question was originally posted on the discussion forum, support and innovations for the site programmers.

    3 answers 3

    create an empty array

     $out = array(); 

    we fill it on the contrary, the keys become values, and the values ​​are keys

     foreach($cart as $key => $value){ $out[$value][] = $key; } 

    go around the resulting array, and if it has more than 1 value, create a string

     foreach($out as $key => $value){ if(count($value) > 1) echo "srt_" . $key ." = (" . implode(",", $value) . ")"; } 
    • Many thanks to all, it turned out. - Hamo
    • Thank you for the thank you, accept the answer :) - Sergey Panasenko
     $out = array(); foreach($cart as $key => $value){ $out["str_".$value][] = $key; } 
       $arr = [1 => 42, 2 => 2.2, 3 => 42, 4 => 5, 6 => 42]; $val = 42; function fn($arr, $n){ return implode(',', array_reduce(array_keys($arr), function($acc, $e) use ($arr, $n){ if($arr[$e] === $n) $acc[] = $e; return $acc; }, [])); } var_dump(fn($arr, $val)); // string(5) "1,3,6" 

      https://repl.it/EfHT/0