Can you tell me why I get this error please.?

17,16,21,2,5,13,11,10,7,14,8,0,18,20,15,1,4,3,6,9,12,19
Fatal error: Maximum execution time of 30 seconds exceeded in /var/www/test_qu2.php on line 3

My code is:
<?php
   function contain($boxValues, $number) {
     for ($k=0; $k<sizeof($boxValues); $k++) {
       if ($boxValues[$k] == $number)
            return true;
     }
       return false;
   }
 
   $num[0] = rand(1,21);
   echo $num [0];
   $boxValues[0] = $num[0];
   for ($i=1; $i<=22; $i++) {      
      $num[$i] = rand(0,21);      
      while (contain($boxValues, $num[$i])) {          
         $num[$i] = rand (0,21);      
      }      
    $boxValues[$i] = $num[$i];    //append into the array  
   
      echo "," .$num[$i];
      }  
     
            
?>
EagleJessAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris Harte2015 Top Expert (Most Article Points)Commented:
You are filling the array, soon it will contain every integer between 1 and 21. Then the while loop will just keep running because it will always be true.
Ray PaseurCommented:
Maybe step back from the technical details of the code and just tell us in plain language what you want to accomplish here?  There are almost certainly built-in PHP functions to do these things.  Thanks.
Julian HansenCommented:
It looks like you are trying to randomize an array.

Why not use the shuffle function http://php.net/manual/en/function.shuffle.php

<?php
$result = range(0,21);
shuffle($result);
var_dump($result);

Open in new window

Introduction to R

R is considered the predominant language for data scientist and statisticians. Learn how to use R for your own data science projects.

Ray PaseurCommented:
@julian: That's what I was thinking, too.  But I wasn't sure about value constraints, or uniqueness, etc.  Maybe we can get a bit more explanation.
EagleJessAuthor Commented:
Hi both.

I want to create 22 non-repeating numbers in the range 0-21 and store them in an array.  They have to be displayed in the array using comma separation.  Thanks.
Ray PaseurCommented:
Please see: http://iconoun.com/demo/temp_eaglejess_contain.php

If you do not want the numbers to be in random order, remove the shuffle() statement.
<?php // demo/temp_eaglejess_contain.php
/**
 * http://www.experts-exchange.com/questions/28938272/Can-you-tell-me-why-I-get-this-error-please.html
 *
 * http://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html
 */
error_reporting(E_ALL);

// MAKE AN ARRAY OF UNIQUE RANDOM NUMBERS BETWEEN ZERO AND 21
$nums = range(0,21);
shuffle($nums);

// SHOW THE ARRAY
$str = implode(',', $nums);
echo $str;

Open in new window

Ray PaseurCommented:
And since the next step in learning about arrays involves finding things in arrays, array_search() may be helpful.  All of the PHP array functions are documented in the online man pages linked here:
http://php.net/manual/en/ref.array.php
<?php // demo/temp_eaglejess_contain.php
/**
 * http://www.experts-exchange.com/questions/28938272/Can-you-tell-me-why-I-get-this-error-please.html
 *
 * http://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html
 * http://php.net/manual/en/ref.array.php
 */
error_reporting(E_ALL);

// MAKE AN ARRAY OF UNIQUE RANDOM NUMBERS BETWEEN ZERO AND 21
$nums = range(0,21);
shuffle($nums);

// SHOW THE ARRAY
$str = implode(',', $nums);
echo $str;

// FIND THE LOCATION (KEY) FOR A GIVEN NUMBER
$num = 7;
$key = array_search($num, $nums);
echo PHP_EOL . "The $num is at position $key";

Open in new window

EagleJessAuthor Commented:
Hi Ray
By removing the shuffle the numbers appear to be non random.  I thought i would have to use the rand function.
Ray PaseurCommented:
By removing the shuffle the numbers appear to be non random.
'Zackly! :-)

These are two different functions.  Have a quick look at the PHP man pages.
http://php.net/manual/en/function.shuffle.php
http://php.net/manual/en/function.rand.php

Writing our own sort or randomization functions is interesting as an academic exercise, but nobody would do that today because the built-in functions are faster and are already debugged.
Julian HansenCommented:
@Eaglejess

The shuffle function handles the rand() for you.

As a sidebar - the approach you took of randomizing the array was very inefficient. As you "run out of numbers" the probability of hitting an unselected number drops and the running time of your script increases.

Standard practice when doing this is to perform N iterations and on each iteration you randomly select two indices into the array (in your case a number between 0 and 21) and then just swap those two positions - repeat that as many times as you feel is necessary for your purposes and your array is randomized.

Here is some code to demonstrate the concept
function myShuffle(&$data, $iterations=1000)
{
    $n = count($data) - 1;
    for($i = 0; $i < $iterations; $i++) {
        $a = rand(0, $n);
        $b = rand(0, $n);
        if ($a != $b) {
          $temp = $data[$a];
          $data[$a] = $data[$b];
          $data[$b] = $temp;
        }
    }
}

Open in new window

Ray PaseurCommented:
Purely academic, but here's my take on how to write the PHP shuffle() function...
<?php // demo/temp_eaglejess_shuffle.php
/**
 * What if the PHP shuffle() function did not exist?
 *
 * http://www.experts-exchange.com/questions/28938272/Can-you-tell-me-why-I-get-this-error-please.html
 *
 * http://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html
 * http://php.net/manual/en/ref.array.php
 */
error_reporting(E_ALL);

// A FUNCTION TO REMOVE A RANDOM ELEMENT FROM AN ARRAY AND RETURN IT
function pluck_random_element(&$arr)
{
    if (empty($arr)) return FALSE;

    $arr = array_values($arr);
    $max = count($arr) - 1;
    $ran = rand(0, $max);
    $val = $arr[$ran];
    unset($arr[$ran]);
    return $val;
}

// MAKE AN ARRAY OF UNIQUE NUMBERS BETWEEN ZERO AND 21
$min = 0;
$max = 21;
$nums = range($min, $max);

// SHUFFLE THE UNIQUE NUMBERS BY CHOOSING EACH ONE AT RANDOM
while($min <= $max)
{
    $num = pluck_random_element($nums);
    $shuf[] = $num;
    $min++;
}

// SHOW THE WORK PRODUCT
echo implode(',', $shuf);

// FIND THE LOCATION (KEY) FOR A GIVEN NUMBER
$num = 7;
$key = array_search($num, $shuf);
echo PHP_EOL . "The $num is at position $key";

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
EagleJessAuthor Commented:
Thank for your help guys.  Interesting to see the many takes on the question.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.