PHP repeat action with adding value - php

I am just learning coding, and couldn't find solution for that:
I'm creating a website that shows pictures that are on its server.
$number = $_POST["NR"];
$picture1 = "{$number}.jpg";
echo '<img src="pictures/' . $picture1 . ' ">';
How can I make it to repeat the echo string, but every time add for "$picture1" calculation +1 ? So, that the maximum count would be 40?
Thanks for helping. I know that it is actually easy, but I still don't know how to do it :)

Assuming that you have images named correctly awaiting this to happen:
$number = $_POST["NR"];
$i = 0;
while ($i < 40) {
$picture = $number + $i.".jpg";
echo '<img src="pictures/' . $picture . ' ">';
$i++;
}
Use a counter and loop. The issue here is that your $number could be anything... For instance if someone passed 500, you would need images named, 500.jpg, 501.jpg, etc. all the way up to 540.jpg. Unless I misunderstood the question.

Related

Random generator returning endless duplicates

I am trying to create a random string which will be used as a short reference number. I have spent the last couple of days trying to get this to work but it seems to get to around 32766 records and then it continues with endless duplicates. I need at minimum 200,000 variations.
The code below is a very simple mockup to explain what happens. The code should be syntaxed according to 1a-x1y2z (example) which should give a lot more results than 32k
I have a feeling it may be related to memory but not sure. Any ideas?
<?php
function createReference() {
$num = rand(1, 9);
$alpha = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 1);
$char = '0123456789abcdefghijklmnopqrstuvwxyz';
$charLength = strlen($char);
$rand = '';
for ($i = 0; $i < 6; $i++) {
$rand .= $char[rand(0, $charLength - 1)];
}
return $num . $alpha . "-" . $rand;
}
$codes = [];
for ($i = 1; $i <= 200000; $i++) {
$code = createReference();
while (in_array($code, $codes) == true) {
echo 'Duplicate: ' . $code . '<br />';
$code = createReference();
}
$codes[] = $code;
echo $i . ": " . $code . "<br />";
}
exit;
?>
UPDATE
So I am beginning to wonder if this is not something with our WAMP setup (Bitnami) as our local machine gets to exactly 1024 records before it starts duplicating. By removing 1 character from the string above (instead of 6 in the for loop I make it 5) it gets to exactly 32768 records.
I uploaded the script to our centos server and had no duplicates.
What in our enviroment could cause such a behaviour?
The code looks overly complex to me. Let's assume for the moment you really want to create n unique strings each based on a single random value (rand/mt_rand/something between INT_MIN,INT_MAX).
You can start by decoupling the generation of the random values from the encoding (there seems to be nothing in the code that makes a string dependant on any previous state - excpt for the uniqueness). Comparing integers is quite a bit faster than comparing arbitrary strings.
mt_rand() returns anything between INT_MIN and INT_MAX, using 32bit integers (could be 64bit as well, depends on how php has been compiled) that gives ~232 elements. You want to pick 200k, let's make it 400k, that's ~ a 1/10000 of the value range. It's therefore reasonable to assume everything goes well with the uniqueness...and then check at a later time. and add more values if a collision occured. Again much faster than checking in_array in each iteration of the loop.
Once you have enough values, you can encode/convert them to a format you wish. I don't know whether the <digit><character>-<something> format is mandatory but assume it is not -> base_convert()
<?php
function unqiueRandomValues($n) {
$values = array();
while( count($values) < $n ) {
for($i=count($values);$i<$n; $i++) {
$values[] = mt_rand();
}
$values = array_unique($values);
}
return $values;
}
function createReferences($n) {
return array_map(
function($e) {
return base_convert($e, 10, 36);
},
unqiueRandomValues($n)
);
}
$start = microtime(true);
$references = createReferences(400000);
$end = microtime(true);
echo count($references), ' ', count(array_unique($references)), ' ', $end-$start, ' ', $references[0];
prints e.g. 400000 400000 3.3981630802155 f3plox on my i7-4770. (The $end-$start part is constantly between 3.2 and 3.4)
Using base_convert() there can be strings like li10, which can be quite annoying to decipher if you have to manually type the string.

Add increasing number to filename, how not to loop?

I'm trying to modify a script that generates random numbers to filenames and instead have a pretty increasing counter of +1 each new file
The original function is very simple it looks like this:
$name .= generateRandomString(5);
What I've came up with my mediocre skills is:
$name .= $count = 1; while ($count <= 10) { echo "$count "; ++$count; }
However, what happens when I run the code is that it just keeps on looping. I was looking for a function similar to the: generateRandomString but for increasing numbers, is there any?
Any ideas?
user current timestamp in place of $count, it will always keep increasing.
$name .= time()

Make an equation in php

I have a php file where i want to make an equation with the output i get.
It is pretty easy if the line is like this:
<?php echo round(($post['voteup']/($post['voteup'] + $post['votedown'] ))*100); ?>
But i have a php line where it goes like this, and i just can't figure out how to make the equation work:
$str='';
$data = $dbc->query($sql);
if($data!=null && $data->num_rows>0){
while( $row = $data->fetch_array(MYSQLI_ASSOC)){
$str.="<p>".$row['voteup']." + ".$row['votedown'].</p>";
}
It may be a silly question, but this really bothers me.
If you want to add the upvotes and downvotes you would do this -
$newTotal = $row['voteup'] + $row['votedown'];
$str.="<p>" . $newTotal ."</p>";
If you are trying to add $row['voteup'] and $row['votedown'] together you should addition them in a variable first then use it.
$total = $row['voteup'] + $row['votedown'];
$str .= "<p>{$total}</p>";
If you really need to make it inline you can do something like this as well.
$str .= '<p>' . ($row['voteup'] + $row['votedown']) . '</p>';
If you just want to display the "equation" simply fix the error.
$str.="<p>".$row['voteup']." + ".$row['votedown']."</p>";
Or you could actually turn it into an equation:
$str.="<p>".$row['voteup']." + ".$row['votedown']." = ".($row['voteup'] + $row['votedown'])."</p>";

how to generate a random image output

i have some basic php code that pulls an image from a particular image folder when the user asks using a form.
I will have many image folders and want to generate a random image instead of using
case 'A' : echo "<a href=\"Alphabet-Letters/Letters-A\">
<img src=\"image/data/A/A_001.jpg\" id=\"A1\" width=\"70\" height=\"120\" title=\"A1\"/> </a>" ; break;
My question is this as the form is processed with someone using the letter A the picture of that letter appears. The php code for this is
if (array_key_exists('check_submit', $_POST))
{
$letters = $_POST['Comments'];
$num_letters = strlen($letters);
for($i = 0; $i < $num_letters; $i++)
{
switch ($letters[$i]) {
case 'A' : echo "<a href=\"Alphabet-Letters/Letters-A\">
<img src=\"image/data/A/A_001.jpg\" id=\"A1\" width=\"70\" height=\"120\" title=\"A1\" alt=\"Image A\"/>
</a>" ;
break;
This only pulls the exact image i have asked, but i have hundreds in that folder and would like a more simple code to work with.
Please can someone help, they gave advise on using random image from folder, but that only works as a starting point not on the code I already have.
Thanks for your time
The solution posted at the link below should achieve the functionality you are looking for.
https://stackoverflow.com/a/4478788/1152375
so you should be able to do something like
case 'A' : echo "<a href=\"Alphabet-Letters/Letters-A\">
<img src=\"image/data/A/" . random_pic("folder_with_pics") . "\" id=\"A1\" width=\"70\" height=\"120\" title=\"A1\</a>";
break;
before you get to the output code, you will want to get a list of all files in the relevent directory ( http://php.net/manual/en/function.dir.php ) in a numbered array.
count the number of items in the array ( http://php.net/manual/en/function.count.php ) and randomly pick one ( http://php.net/manual/en/function.rand.php ) using the min and max settings of rand.
Try using the scandir function to find all the files in the folder, and then use the rand function to randomly choose one:
if(!empty($_POST['check_submit']))
{
$letters = strtoupper(trim($_POST['Comments']));
$num_letters = strlen($letters);
for($i = 0; $i < $num_letters; $i++)
{
$letter = $letters[$i];
$folder = 'image/data/'.$letter;
$files = scandir($folder);
array_shift($files);
array_shift($files);
$index = rand(0, count($files) - 1);
$file = $files[$index];
echo "<a href=\"Alphabet-Letters/Letters-{$letter}\">\n";
echo "<img src=\"image/data/{$letter}/{$file}\" id=\"{$letter}{$index}\" width=\"70\" height=\"120\" title=\"{$letter}{$index}\" alt=\"Image {$letter}\"/>\n";
echo "</a>\n";
}
}
Found the answer by using #Buchow_php and trial and error.
for ($i=0; $i<$num_letters; $i++)
{
$image_num = '$image'.$i;
echo "<input type=\"hidden\" name=\"option[$image_num]\" value=\"$skus[$i]\" />";
}
together with the previous code and now it brings all the image files into an array for posting to my submit

Run A PHP function only 30% of Time

I need help creating PHP code to echo and run a function only 30% of the time.
Currently I have code below but it doesn't seem to work.
if (mt_rand(1, 3) == 2)
{
echo '';
theFunctionIWantCalled();
}
Are you trying to echo what the function returns? That would be
if(mt_rand(1,100) <= 30)
{
echo function();
}
What you currently have echoes a blank statement, then executes a function. I also changed the random statement. Since this is only pseudo-random and not true randomness, more options will give you a better chance of hitting it 30% of the time.
If you intended to echo a blank statement, then execute a function,
if(mt_rand(1,100) <= 30)
{
echo '';
function();
}
would be correct. Once again, I've changed the if-statement to make it more evenly distributed. To help insure a more even distribution, you could even do
if(mt_rand(1,10000) <= 3000)
since we aren't dealing with true randomness here. It's entirely possible that the algorithm is choosing one number more than others. As was mentioned in the comments of this question, since the algorithm is random, it could be choosing the same number over, and over, and over again. However, in practice, having more numbers to choose from will most likely result in an even distribution. Having only 3 numbers to choose from can skew the results.
Since you are using rand you can't guarantee it will be called 30% of the time. Where you could instead use modulus which will effectively give you 1/3 of the time, not sure how important this is for you but...
$max = 27;
for($i = 1; $i < $max; $i++){
if($i % 3 == 0){
call_function_here();
}
}
Since modulus does not work with floats you can use fmod, this code should be fairly close you can substitute the total iterations and percent...
$total = 50;
$percent = 0.50;
$calls = $total * $percent;
$interval = $total / $calls;
$called = 0;
$notcalled = 0;
for($i = 0; $i <= $total; $i++){
if(fmod($i, $interval) < 1){
$called++;
echo "Called" . "\n";
}else{
$notcalled++;
echo "Not Called" . "\n";
}
}
echo "Called: " . $called . "\n";
echo "Not Called: " . $notcalled . "\n";

Categories