Home > Backend Development > PHP Tutorial > PHP custom function implements the function of randomly exchanging elements in an array

PHP custom function implements the function of randomly exchanging elements in an array

墨辰丷
Release: 2023-03-31 12:18:02
Original
1646 people have browsed it

This article mainly introduces the custom function to realize the function of randomly exchanging elements in the array. Interested friends can refer to it. I hope it will be helpful to everyone.

The example in this article describes how PHP randomly swaps elements in an array. The specific analysis is as follows:

This is a custom PHP function that randomly swaps array elements. PHP already has a built-in function shuffle($Array) with the same function. This code should be referred to

// I noticed that there is already a built-in function that
// does the same - so don't use mine ;-)
//
// --> shuffle($Array);
//
// http://de2.php.net/manual/de/function.shuffle.php
//
function RandomizeArray($array){
  // error check:
  $array = (!is_array($array)) ? array($array) : $array;
  $a = array();
  $max = count($array) + 10;
  while(count($array) > 0){    
    $e = array_shift($array);
    $r = rand(0, $max);
    // find a empty key:
    while (isset($a[$r])){
      $r = rand(0, $max);
    }    
    $a[$r] = $e;
  }
  ksort($a);
  $a = array_values($a);
  return $a;
}
Copy after login

Usage example:

/*
** Example:
*/
$test_array = array('why','dont','visit','www','jonas','john','de',':-)');
print implode(", ", $test_array);
print "\n";
print implode(", ", RandomizeArray($test_array));
/*
Example output:
why, dont, visit, www, jonas, john, de, :-)
www, de, jonas, john, visit, why, :-), dont
*/
Copy after login

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's learning.

Related recommendations:

php method of regular matching and replacing callback content tags

php is implemented on the server Complete the image size adjustment on the end

PHP regular expression method to verify Email

The above is the detailed content of PHP custom function implements the function of randomly exchanging elements in an array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template