How to convert range of generated alphanumeric code into an array

51 Views Asked by At
 The below code is what I have written
<?php
 $pincode="" ;
function getPinCode($length){
 $pincode = "";
 $codeAlphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 $codeAlphabet.= "0123456789";

 $max = strlen($codeAlphabet); // edited
 for ($i=0; $i < $length; $i++) {
    $pincode.= $codeAlphabet[random_int(0, $max-1)];//to output the combined code
 implode('', $pincode)// to convert the code to array
 $pincode= array()//explicitly declare $pincode var
 }
​return $pincode;
 }

for ($n=0;$n<8; $n++){
echo getPinCode(11);
echo ", ";
print_r($pincode);
}?>

//If I run the above it gives errors 1. Array to string conversion 2. Implode() invalid argument passed. If I comment on those two lines where the errors /originate it generates 8 different codes but not as an array.

I want to do is to generate a set of codes /using php and make them into an array. Please where exactly did I go wrong. Thanks a million ​

2

There are 2 best solutions below

0
On

You could simply assign to a $pincode array the random values

for ($i=0; $i < $length; $i++) {
   $pincode[$i]= $codeAlphabet[random_int(0, $max-1)];//array of the code 
}
2
On
 implode('', $pincode)// to convert the code to array
 $pincode= array()//explicitly declare $pincode var

You're not assigning the return value of implode then you're just creating an empty array for $pincode.