I want the array to be sorted randomly, I made the condition that if there is such an element in the array, it is not added again, but for some reason it is added

<?php error_reporting(-1); $arr = [ 'African elephant', 'Spotted hyena', 'Snow leopard', ]; echo '<pre>'; var_dump($arr); echo '<pre>'; $new_arr = []; $count = count($arr); for($i = 0; $i < count($arr); $i++){ if (in_array($arr[$i], $new_arr)) { !array_push($new_arr, $arr[rand(0, count($arr)-1)]); } else{ array_push($new_arr, $arr[rand(0, count($arr)-1)]); } } var_dump($new_arr); 
  • 3
    And what does the finished function shuffle not do? php.net/manual/ru/function.shuffle.php - user239133
  • Your exclamation point is a simple unary operator, applied to the result of the insert call to the array. Do not call the array_push function array_push all in this thread. - vp_arth
  • one
    I need my function if I use everything ready, but I don’t learn anything - DivMan

3 answers 3

 <?php $arr = [ 'African elephant', 'Spotted hyena', 'Snow leopard', ]; shuffle($arr); echo '<pre>'; var_dump($arr); echo '</pre>'; 
  • That was not my tag)) Thanks for the signal - fixed. - Edward
  • I need my function - DivMan
  • @DivMan then use the array_rand () and unset () combination of the obtained value. - Edward
  • and where does unset ()? - DivMan
  • @DivMan despite the fact that in order to avoid repetitions, randomly selected elements of the array should be deleted. - Edward
 <?php $arr = [ 'African elephant', 'Spotted hyena', 'Snow leopard', ]; $arrNew = []; while (count($arr) > 0) { $key = array_rand($arr); $arrNew[] = $arr[$key]; unset($arr[$key]); } echo '<pre>'; var_dump($arrNew); echo '</pre>'; 
  • Why is the condition greater than 0? - DivMan
  • array_rand function, can i make it from rand? - DivMan
  • @DivMan Why is the condition greater than 0? Read the manual, the principle of the cycle while (true) {}. The answer to your question is because the loop will continue to iterate until the count () value is less than one. - Edward
  • array_rand function, can i make it from rand? not. - Edward
  • one
    @Edward, in PHP arrays are hashes in which elements are linked into a list. Extracting an element from an array by index is O (1), from the list is O (N). If the conditions and implementation of the problem are known to have only integer keys in the $ a hash, and they go continuously from 0 to count ($ a) -1, then you can use $ a [rand (0, count ($ a) -1) ], and it will be faster than array_rand. - user239133

Here is another implementation. Translated from Java .

 <?php function shuffle_array($arr){ for($i = count($arr) - 1; $i > 0; $i--){ $index = mt_rand(0, $i); $val = $arr[$index]; $arr[$index] = $arr[$i]; $arr[$i] = $val; } return $arr; } $arr = [ 'African elephant', 'Spotted hyena', 'Snow leopard', ]; var_dump(shuffle_array($arr));