It is necessary to fulfill the condition when iterating through the array, depending on whether there is an element in the array or not.

foreach ($arr as $items) { // Здесь, если первый элемент массива со значением name, // то выполнить одно условие, если это второй элемент // со значением name то выполнить другое условие. } 
  • one
    Use the array_search function; it returns the index in the array or null. Well, then we check for null and fulfill the condition depending on the returned value - Vadim Prokopchuk

2 answers 2

It all depends on how much this array, and what to do with the elements that are repeated.

I would suggest to do this: go through all the elements of the array and build an array, where the keys will be the values, the values ​​will be the keys of the original array:

 $array = [...]; //это общий массив с исходными данными $arraySpecial = []; //это будет как раз учетный массив foreach($array as $key => $value) { $arraySpecial[$value][] = $key; unset($array[$key]); //чтобы не дублировать данные, можно удалить их, все равно ключи (т.е. значения массива с исходными данными) все равно будут идти в нужном порядке } 

Actually everything, now you have an array of $ arraySpecial which contains all the statistics on your initial array.

Execution Example:

 $array = ['as'=>1, 'sd'=>0, 'wer'=>1, 'were'=>4, 'dfg'=>1, 'cvb'=>3, 'rte'=>0, 'cvb'=>2]; $arraySpecial = []; foreach ($array as $key => $value) { $arraySpecial[$value][] = $key; unset($array[$key]); } print_r($arraySpecial); 

Result:

 Array ( [1] => Array ( [0] => as [1] => wer [2] => dfg ) [0] => Array ( [0] => sd [1] => rte ) [4] => Array ( [0] => were ) [2] => Array ( [0] => cvb ) ) 

    for starters, you can use the advanced foreach construct:

     foreach($arr as $key => $value) { // все остальное }