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

EagleJess
EagleJess used Ask the Experts™
on
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];
      }  
     
            
?>
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
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.
Most Valuable Expert 2011
Top Expert 2016

Commented:
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.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
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

Announcing the Winners!

The results are in for the 15th Annual Expert Awards! Congratulations to the winners, and thank you to everyone who participated in the nominations. We are so grateful for the valuable contributions experts make on a daily basis. Click to read more about this year’s recipients!

Most Valuable Expert 2011
Top Expert 2016

Commented:
@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.

Author

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.
Most Valuable Expert 2011
Top Expert 2016

Commented:
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

Most Valuable Expert 2011
Top Expert 2016

Commented:
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

Author

Commented:
Hi Ray
By removing the shuffle the numbers appear to be non random.  I thought i would have to use the rand function.
Most Valuable Expert 2011
Top Expert 2016

Commented:
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.
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
@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

Most Valuable Expert 2011
Top Expert 2016
Commented:
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

Author

Commented:
Thank for your help guys.  Interesting to see the many takes on the question.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial