There is an associative array. You need to select specific values ​​by coincidence and I would like to do all this without a loop, since arrays can be large, tell me how this can be done? For example:

0 =>[ 'user'=> 'ivan' 'amount' => 50 'date' => '2019' ], 1=> [ 'user'=> 'dima' 'amount' => 10 'date' => '2019' ], 2=> [ 'user'=> 'ivan' 'amount' => 11 'date' => '2019' ], 

I need to leave for example ivan and in order to get this at the output:

 0 =>[ 'user'=> 'ivan' 'amount' => 50 'date' => '2019' ], 1=> [ 'user'=> 'ivan' 'amount' => 11 'date' => '2019' ], 
  • Where is your code? At least try. - doox911 am
  • @ doox911 I can do it and my code with the cycle will not be appropriate here, I want to know if it is possible to do it without a cycle - Evgeny Kolesnik

3 answers 3

It should be understood that if the cycle is not explicitly registered in the script, this does not mean that there will be no cycle at all. It should also be understood that in principle it is impossible to loop through an array without a loop. That is, the cycle will be, regardless of the wishes of the author of the question.

You should also understand that in pursuit of optimization, you can get a result that is directly opposite to the expected. What we have in this case is that in an attempt to avoid one cycle, the author of the question received two answers in one of the answers: one cycle to iterate over the source array, and the second cycle to iterate over the resultant array.

Moral: the task of searching in an array without a loop does not make sense.

  • yes you are right, but I tested the result is not significant for example, I created an array of 100,000 records and I got the following results float (0.53402996063232) - array_filter and float (0.49602890014648) - foreach - Eugene Kolesnik

do it all without looping

You can filter the array with array_filter () , and reset the keys with array_values ​​() :

 $arr = [ [ 'user'=> 'ivan', 'amount' => 50, 'date' => '2019' ], [ 'user'=> 'dima', 'amount' => 10, 'date' => '2019' ], [ 'user'=> 'ivan', 'amount' => 11, 'date' => '2019' ] ]; $arr = array_values(array_filter($arr, function($a){ return in_array('ivan', $a); })); print_r($arr); 

Result:

 Array ( [0] => Array ( [user] => ivan [amount] => 50 [date] => 2019 ) [1] => Array ( [user] => ivan [amount] => 11 [date] => 2019 ) ) 

    thanks, a little refined, it seems to me without the additional function in_arr will be faster

     $search = 'ivan'; $res = array_filter($arr, function($v) use ($search){ return $v['user'] == $search; }); 
    • like this (without type checking) it will be faster: return $v['user'] == $search; - Edward