Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I repeat a function (x times, each time unique output)?

Tags:

php

I'm trying to create an app that will repeat a function X number of times. Each time, the function will generate a random number. Once it generates the code, the code would then create an array with the new random numbers. Any help would be appreciated.

I have the code that create the random number and hyphenates it, but I'm having trouble calling the function cardNumber to repeat itself x number of times and put the results in an array.

function hyphenate($str) {
    return implode("-", str_split($str, 4));
}

function cardNumber() { 
    for ($s = '', $i = 0, $z = strlen($a = 'ABCDEFGHJKLMNOPQRSTUVWXYZ')-1; $i != 2; $x =      rand(0,$z), $s .= $a{$x}, $i++);

    $uid = uniqid(true);
    $ccn = substr_replace($uid, $s, 0, 0);
    $upperccn = strtoupper($ccn);
    $editedccn = hyphenate($upperccn);
    return $editedccn;
};

$array = array(str_repeat(cardNumber(), 2));
var_dump ($array);
like image 710
user1985117 Avatar asked Jan 16 '13 20:01

user1985117


3 Answers

Just use a loop:

$i = 0;
$times_to_run = 16;
$array = array();
while ($i++ < $times_to_run)
{
    $array[] = cardNumber();
}
like image 62
John Conde Avatar answered Sep 27 '22 17:09

John Conde


Here's a more readable approach that's also easier to type

foreach(range(1,20) as $i) { 
   ...
}
like image 35
murze Avatar answered Sep 27 '22 18:09

murze


$num = amount of times to execute
for($i =0; $i < $num; $i++){
    $array[] = cardNumber();
}
#then
var_dump($array);
like image 21
Class Avatar answered Sep 27 '22 17:09

Class