Home > Backend Development > PHP Tutorial > PHP randomly assigns a specified number to an array of specified books

PHP randomly assigns a specified number to an array of specified books

WBOY
Release: 2016-08-08 09:30:32
Original
923 people have browsed it
<?php
$num = 5;
$total = 20;
function randArray($num,$total){
&#160;&#160; &#160;$array = array();
&#160;&#160; &#160;$array = array_pad($array,$num,0);
&#160;&#160; &#160;for($i=0;;$i++){
&#160;&#160; &#160;&#160;&#160; &#160;for($j=0;$j<$num;$j++){
&#160;&#160; &#160;&#160;&#160; &#160;$rand = rand(0,1);
&#160;&#160; &#160;&#160;&#160; &#160;if( (array_sum($array) + $rand) >= $total ){
            $array[$j] += $total - array_sum($array);
            return $array;
        }else{
            $array[$j] += $rand;
        }
        }
    }
}

$array = randArray($num,$total);
echo '<pre class="brush:php;toolbar:false">';
print_r($array);
echo '<br />';
echo array_sum($array);
echo '<br />';
$key = array_rand($array);
echo $key;
echo '<br />';
echo $array[$key];
Copy after login

The above introduces how PHP randomly allocates a specified number to an array of specified books, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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