I have typed this up to generate a random code. I am trying to add them into a database as they are generated. How do i modify this code to generate x amount instead of one?
<?php
$tokens = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$serial = '';
for ($i = 0; $i < 4; $i++) {
for ($j = 0; $j < 5; $j++) {
$serial .= $tokens[rand(0, 35)];
}
if ($i < 3) {
$serial .= '-';
}
}
echo '<p>' . $serial;
?>
for more precise random token. Try adding current timestamp with a text. current Timestamp itself changes every second. therefore it will mostly be unique. A random text adding at front or last can make it even more unique for users working at a same time.
UPDATE: also add a function whether that unique string exists or not.
A pretty cool, easy method, can be something like this too.
<?php
echo md5(microtime());
Ofcourse it is not 100% safe etc but if you need a quick and easy "RANDOM" string it could be usefull.
Concerning your question:
<?php
function genereteRandomKey($count=10)
{
$data = [];
for($i=0;$i<$count;$i++)
{
$data[] = md5(microtime());
}
return $data;
}
var_dump(generateRandomKey());
To do this, we edit your code slightly and wrap it within a function, like this;
function createHash($length = 4)
{
$tokens = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$serial = '';
for ($it = 0; $it < $length; $it++) {
$serial .= $tokens[ mt_rand( 0, (strlen($tokens) - 1) )];
}
return $serial;
}
The length within the parameter can be left null and will default to 4, just in case you wanted to create longer codes.
To then create more codes, you simply loop via a for loop (Or any loop that you are using!) like so;
for ($i = 0; $i < 5; $i++) {
echo createHash() . '<br />';
}
Obviously, you won't be wishing to echo them out, but instead adding them to a database.
With that in mind, may I also suggest that instead of multiple INSERT queries, to catch them all inside of an array and just do one run on the query, which can be achieved like so;
$inserts = array ();
for ($i = 0; $i < 5; $i++) {
$inserts[] = createHash();
}
$sql = "INSERT INTO `table` (`row`) VALUES ('" . implode('\'), (\'', $inserts) . ");";
Which, in that test run, would output the following as your $sql;
INSERT INTO `table` (`row`) VALUES ('ISS7'), ('SB72'), ('N97I'), ('1WLQ'), ('TF6I);
Related
Forgive the word game.
I have to cycle an array and sum the values, then multiply for the price (i already know how to do that).
The object is composed of 64 fields called val1, val2, val3 etc .. each field has a simple_array with the value of the quantity.
I get these data from the database using doctrine.
$item = $this->getDoctrine()->getRepository(ExpertationsAdvanced::class)->findBy(['father' => $id]);
dump($item[0]->getVal1());
for($i = 1; $i < 64; $i++) {
dump(${'$item[0]->getVal' . $i . '()'});
$i++;
if(${'$item[0]->getVal' . $i . '()'} == null) {
$return = '0';
} else {
$return = array_sum(${'$item[0]->getVal' . $i . '()'} );
}
dump($return);
}
the first dump return the array i'm requesting for, with no problems, but in the forloop, i get erro Notice: Undefined variable: $item[0]->getVal1().
I think I'm using the wrong logic but maybe worked so mutch time and can't see a way.
First of all if you have 64 fields, you should have(read docs for more info):
for($i = 1; $i <= 64; $i++) {
Secondary, you don't need to increment $i inside of loop
$i++;
To get the value:
$item[0]->{"getVal{$i}"}();
// OR
$method = "getVal{$i}";
$item[0]->$method();
Result will be:
for($i = 1; $i <= 64; $i++) {
$array = $item[0]->{"getVal{$i}"}();
$return = is_array($array) ? array_sum($array) : 0;
dump($return);
}
I want to generate a unique value with a length of 12 characters. To generate unique values, I use this method:
function generate_unique_id()
{
$time = substr(time(), -7);
$month = mb_strtolower(date("M"));
$symbol = "OM";
$string = $month."".$time."".$symbol;
$result = str_shuffle($string);
return $result;
}
I tested this code to generate 30,000 unique values, but each time the loop is exited without generating the required unique identifiers.
$array = [];
for($i=0; $i<=3; $i++)
{
$unique_id = generate_unique_id();
if(in_array($unique_id, $array)){
echo $i;
break;
}
$array[] = $unique_id;
}
How can I know the number of generated unique values with a length of 12 character strings and quickly generate a unique value if the generation capability has not reached the maximum number limit.
The code below generated 30,000 unique IDs in 21.3783249855041 seconds.
$ids = [];
while (count($ids) < 30000) {
$id = bin2hex(random_bytes(6));
if (!in_array($id, $ids)) array_push($ids, $id);
}
var_dump(count($ids));
var_dump($ids);
The code above will continue generating IDs until it gets 30,000 unique IDs, there is no reason to break.
1Generation time may vary.
Live Example
Repl
Update #1
For those that don't have PHP 7 available, you can use this function.
Update #2
This snippet is massively more efficient, as per #cckep comment:
$time_start = microtime(true);
$ids = [];
while (count($ids) < 30000) {
$id = bin2hex(random_bytes(6));
if (!isset($ids[$id])) $ids[$id] = true;
}
$ids = array_keys($ids);
$time_end = microtime(true);
$execution_time = ($time_end - $time_start);
var_dump(count($ids));
var_dump($ids);
echo $execution_time;
Untested, should work though (random prefix + hex-counter suffix):
<?php
function unique_id($length = 12)
{
static $counter = 0;
$suffix = dechex($counter);
$prefixLen = $length - strlen($suffix);
$prefix = substr(uniqid(), -$prefixLen);
$counter++;
return $prefix.$suffix;
}
$arr = array();
for ($i = 0; $i < 30000; $i++)
{
$id = unique_id();
if (in_array($id, $arr))
{
echo $id."\n";
break;
}
$arr[]= $id;
}
echo "Generated ".count($arr)." unique IDs.\n";
Note that this only works if you need all those IDs in one request / script execution. A new request would cause the static $counter variable to start anew, which doesn't guarantee unique ids anymore.
I have a function which gets some values from Google analytics and prints them to the screen. I need to use these values later on in the file. When i try to assign these values to a variable it is null but the print is displaying the values correctly. An example of the values being printed is
3188, 2530, 2475, 1340, 2184.
function printResults($reports){
global $anna;
for ($j = 0; $j < count($metrics); $j++) {
$values = $metrics[$j]->getValues();
for ($k = 0; $k < count($values); $k++) {
$entry = $metricHeaders[$k];
print($values[$k] . ", ");
$anna.=$values[$k]. ", ";
}
}
}
So the vaules correctly display using the print but when i try to echo the variable $anna outside of the function it does not.
Ok so after looking at the solution from Don't Panic it became obvious that the variable just needed to be returned. Who would have thought it :) Thanks for the help!
for ($j = 0; $j < count($metrics); $j++) {
$values = $metrics[$j]->getValues();
for ($k = 0; $k < count($values); $k++) {
$entry = $metricHeaders[$k];
//print($values[$k] . ", ");
$anna.=$values[$k]. ", ";
return $anna;
}
I would suggest a different approach. It looks like your function gets all the values from a set of metrics that each contains a set of values, and prints them. If you need to use the set of values, then your function that directly prints them isn't as useful. Make a function that just gets the values and returns them in an array. Be sure to return them!
function getAllValues($metrics) {
foreach ($metrics as $metric) {
foreach ($metric->getValues() as $value) {
$allValues[] = $value;
}
}
return $allValues;
}
I'm assuming the $reports argument in the example in your question is supposed to be $metrics.
Then, you can call this function to get your values.
$values = getAllValues($metrics);
And if you need to print them, just
echo implode(', ', $values);
That way your function does what it says it does.
I am trying to make this code small using for or while loop . It is working with the following code,I just want this to be small. 'ufile' is the input name.
if (!$_FILES['ufile']['name'][0])
{
echo "Upload 1st file";
}
else
{
// can this be in a for loop???
$path1= "../uploads/".$_FILES['ufile']['name'][0];
$path2= "../uploads/".$_FILES['ufile']['name'][1];
$path3= "../uploads/".$_FILES['ufile']['name'][2];
$path4= "../uploads/".$_FILES['ufile']['name'][3];
$path5= "../uploads/".$_FILES['ufile']['name'][4];
$path6= "../uploads/".$_FILES['ufile']['name'][5];
$path7= "../uploads/".$_FILES['ufile']['name'][6];
$path8= "../uploads/".$_FILES['ufile']['name'][7];
}
$path = array();
for($i=0;$i<=7;++$i)
$path[$i]="../uploads/".$_FILES['ufile']['name'][$i];
I would advise against your current coding style. Life would be simpler if you just stored the paths in an array, e.g.
$paths[1] = "../uploads/" . $_FILES['ufile']['name'][0];
$paths[2] = "../uploads/" . $_FILES['ufile']['name'][1];
Then you could do something like this:
$paths = array();
for ($i = 0; $i <= 7; $i++) {
$paths[$i + 1] = $_FILES['ufile']['name'][$i];
}
But to answer your question, you can do something like this instead, which is very similar:
$paths = array();
for ($i = 0; $i <= 7; $i++) {
$paths['path' . ($i + 1)] = $_FILES['ufile']['name'][$i];
}
extract($paths);
See the extract doc page for more info about what's going on here
You can use variable variables as well :
foreach(range(0,7) as $index){
$varname = "path".$index;
$$varname = "../uploads/".$_FILES['ufile']['name'][$index];
}
Not sure what you want to do with those paths afterwards but here is my go at it. I would use the length of the array, assuming it doesn't always contain the same amount of file names.
$paths = array();
for($i = 0; $i < count($_FILES['ufile']['name']); $i++)
{
$paths[] = "../uploads/".$_FILES['ufile']['name'][$i];
}
I need to add * in an array. This is how i do it in javaScript.
function makeStarString(grade) {
var starArray = [];
var starString = "";
for (var i = 0; i < grade; i++){
starArray[i] = "*";
starString = starString.concat(starArray[i]);
}
return starString;
}
The javascript version works fine but I cant make it work with php.
This is as far as i got with php.
function makeStarString($varGrade) {
$starArray = array ();
$starString = "";
for ($i = 0; $i < strlen($varGrade); $i++){
$starArray($i) = $star;
$starString = $starString.(starArray(i));
}
return $starString;
}
I get this error "Fatal error: Can't use function return value in write context" because of line $starArray($i) = $star;
The argument I send to the function is an Integer.
So the purpose of the function is that if i send a 5 to the function it will return *****
How can i fix my php function?
Use $starArray[$i] instead of $starArray($i) and starArray(i).
If you really need stars in an array, you don't need to use a loop:
$starArray = array_fill(0, $varGrade, '*');
and if you need to turn the array into a string:
$starString = implode('', $starArray);
But if you don't really ever need to use the array of stars, it would be easier to just use str_repeat:
str_repeat('*', $varGrade);
It would generally be a great idea to use strlen($varGrade) in a variable, because the foreach loop will have to count the length every iteration. This might bring performance issues.
Your $star variable is not defined, so I have no idea what you're trying to put there. Revise your own code.
Finally, you may use the .= operator to add something to existing string.
function makeStarString($varGrade) {
$starArray = array ();
$starString = "";
$length = strlen($varGrade);
for ($i = 0; $i < $length; $i++){
$starArray[$i] = $star;
$starString .= $starArray[$i];
// equivalent to $starString = $starString . $starArray[$];
}
return $starString;
}
UPDATE
If you send an int to the function, you don't need strlen:
function makeStarString($varGrade) {
$starArray = array ();
$starString = "";
for ($i = 0; $i < $varGrade; $i++){
$starArray[$i] = $star;
$starString .= $starArray[$i];
// equivalent to $starString = $starString . $starArray[$];
}
return $starString;
}
This code should work
function makeStarString($varGrade) {
$star = "*"; // star variable wasn't defined to.
$starArray = array ();
$starString = "";
for ($i = 0; $i < $varGrade; $i++){
$starArray[$i] = $star; // [ ] instead of ( )
$starString .= ($starArray[$i]); // $a.=$b instead of $a=$a+$b, added the $ at the i and [ ] instead of ( )
}
return $starString;
}
Is this what you need?
function makeStarString($varGrade) {
$starString = '';
for ($i = 0; $i < $varGrade; $i++) {
$starString .= '*';
}
return $starString;
}
A few notes on my modifications.
I don't see why you need that $starArray array in the first place. So I skipped it.
I revised your indentation. Strange indentation can make very simple code seem much more complicated than it really is. :)
You should ask if $i < $varGrade, not if $i < strlen($varGrade). If you ask by strlen(), then you get the width of the number you enter. For example, strlen(55) is 2, strlen(555) is 3, strlen(5555) is 4 etc. - ignoring the fact that it's a number. You just want the for-loop to give you $varGrade many stars so there is no need for strlen().
As a detail, I've put used single-quotes instead of double-quotes for strings because they're lighter (PHP doesn't parse variables inside them).
I hope it helps.