I'm using a php script to randomly show images. I've duplicated this script three times because I wanted to show three random images at once - I'm unsure of how to change the php code to show 3 images.
The problem is, I don't want to run into the chance of all three scripts showing the same images at once. Is there something that I could add to this code to make sure that each image displayed is always different?
<?php
$random = "random.txt";
$fp = file($random);
srand((double)microtime()*1000000);
$rl = $fp[array_rand($fp)];
echo $rl;
?>
the html:
<?php include("rotate.php"); ?>
<?php include("rotate.php"); ?>
<?php include("rotate.php"); ?>
*the random.txt just has a list of filenames with links.
Simple solution...
Get the array of random images (you already did this)
Shuffle the array
Pop an image off the end of the array whenever you need one
rotate.php
$random = "random.txt";
$fp = file($random);
shuffle($fb); //randomize the images
in your code
<?php include('rotate.php') ?>
Whenever you need an image
<?php echo array_pop( $fb ) ?>
http://php.net/manual/en/function.array-pop.php
function GetRandomItems($arr, $count)
{
$result = array();
$rcount = 0;
$arrsize = sizeof($arr);
for ($i = 0; ($i < $count) && ($i < $arrsize); $i++) {
$idx = mt_rand($rcount, $arrsize);
$result[$rcount] = trim($arr[$idx]);
$arr[$idx] = $arr[$rcount];
$rcount++;
}
return $result;
}
$listname = "random.txt";
$list = file($listname);
$random = GetRandomItems($list, 3);
echo implode("<BR>", $list);
P.S. Actually, Galen's answer is better. For some reason I forgot about shuffle xD
You can use array_rand() to select more than one random key at a time, like this:
$random = "random.txt";
$fp = file($random);
shuffle($fp);
// You don't need this. The array_rand() function
// is automatically seeded as of 4.2.0
// srand((double)microtime()*1000000);
$keys = array_rand($fp, 3);
for ($i = 0; $i < 3; $i++):
$rl = $fp[$keys[$i]];
echo $rl;
endfor;
This would eliminate the need for including the file multiple times. It can all be done at once.
You could write a recursive function to check if the array ID has already been printed, and if it has, call itself again. Just put that in a for loop to print three times :)
Though keep in mind that truly random images could overlap!
$beenDisplayed = array();
function dispRand($id) {
if (in_array($id, $beenDisplayed)) {
//generate random number
dispRand($id);
}
else {
array_push($beenDisplayed, $id);
}
}
for ($i = 0; $i < 3; $i++) {
dispRand($random_id);
}
Related
I'm having some doubt doing some for each loop, so i have an immense variable names ranging from $a1 - $a120
What I'm trying to do is doing a for each loop from where I can get each of thoose by using an indexing system.
$a116= "N69";
$a117= "V52";
$a118= "V53";
$a119= "V54";
$a120= "V55";
# FIM
for ($i = 0; $i <= 119; ++$i) {
$var = ${"a".$i}; // This is what i need to learn to do
$sheet->setCellValue($var, $array[$i]); // the array is other information im inserting to the file
}
It is not good for the loops. But you can use it, if you can not change your codes.
I just added
$var_name="a".$i;
$var = $$var_name;
And the full code is below.
$a116= "N69";
$a117= "V52";
$a118= "V53";
$a119= "V54";
$a120= "V55";
# FIM
for ($i = 0; $i <= 119; ++$i) {
$var_name="a".$i;
$var = $$var_name; // This is what i need to learn to do
$sheet->setCellValue($var, $array[$i]); // the array is other information im inserting to the file
}
You should update the code to use an array.
$data = [];
$data["a116"] = "N69";
$data["a117"] = "V52";
$data["a118"] = "V53";
$data["a119"] = "V54";
$data["a120"] = "V55";
Now you can use a foreach loop getting the key/value pairs
foreach($data as $key => $value){
$sheet->setCellValue($key, $value);
}
I want to display random n number of images from a folder. Currently i am using this script to display images
<?php
$dir = './images/gallery/';
foreach(glob($dir.'*.jpg') as $file) { ?>
<div class="item"><img src="<?php=$file;?>"></div>
<?php } ?>
I want only 10 (or n number) images, that too randomly. How to do this?
The shuffle() method will put the elements of a given array in a random order:
<?php
$dir = './images/gallery/';
function displayImgs($dir, $n=10){
$files = glob($dir.'*.jpg');
shuffle($files);
$files = array_slice($files, 0, $n);
foreach($files as $file) { ?>
<div class="item"><img src="<?php=$file;?>"></div>
<?php }
} ?>
Usage:
displayImgs("/dir/temp/path", 20);
Well, this might be overkill, but you can also use a directory iterator and some randomness to achieve this. I used a modified version of the random numbers generation function from this answer.
make sure that the path you give to the function is relative to the directory in which the script resides, with a slash at the beginning. The __DIR__ constants will not change would you happen to call this script from different places in your file hierarchy.
<?php
function randomImages($path,$n) {
$dir = new DirectoryIterator(__DIR__. $path);
// we need to know how many images we can range on
// but we do not want the two special files . and ..
$count = iterator_count($dir) - 2;
// slightly modified function to create an array containing n random position
// within our range
$positionsArray = UniqueRandomNumbersWithinRange(0,$count-1,$n);
$i = 0;
foreach ($dir as $file) {
// those super files seldom make good images
if ($file->getFilename() === '.' || $file->getFilename() === '..') continue;
if (isset($positionsArray[$i])) echo '<div class="item"><img src="'.$file->getPathname().'"></div>';
$i++;
// change the count after the check of the filename,
// because otherwise you might overflow
}
}
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
$numbers = range($min, $max);
shuffle($numbers);
return array_flip(array_slice($numbers, 0, $quantity));
}
Let us first create a array and push some random numbers into it. And as per you let $n be 10.
$n = 10;
$arr = array();
for($i = 1; $i <= $n; $i++){
/* Where $n is the limit */
$rand = rand($n);
array_push($arr, $rand);
}
So now we have an array containing the random digits and now we have to echo out the images by iterating over the array:
foreach($arr as $image){
$intToStr = (string) $image;
foreach(glob($dir. $intToStr . '.jpg') as $file){
echo "<div class='item'>$file</div>";
}
}
This would echo out your images.
i use this code :
<?php include("news/news05.php"); ?>
<?php include("news/news04.php"); ?>
<?php include("news/news03.php"); ?>
<?php include("news/news02.php"); ?>
<?php include("news/news01.php"); ?>
Is there a way to increment the inclusion automaticaly ? like for exemple if i put in my file a new page called "news06.php" ?
btw, is there a way to include many pages with a single line ?
Thank you for your help.
Benj
You could use this solution:
<?php
for ($i = 1; $i <= 6; $i++) {
$fname = "news/news0{$i}.php";
if (file_exists($fname)) {
include($fname);
}
}
?>
Just modify it closer for you needs...
There is no way to write one include for include multi files
Put all the includes in one file and include that, or create loop for this
But in my opinion keep it simple and write one line for each file
When I have to do it, I use this:
$files = glob('news/news*[0-9].php', GLOB_BRACE);
natcasesort($files);
foreach ($files as $newsFile) {
require_once($newsFile);
}
More info at PHP: glob function manual
U can use an itteration for this
ex.
<?php
for ($i=5;$i > 0; $i--) {
include('news/news'.str_pad($i, 2, '0', STR_PAD_LEFT).'.php');
}
This should work for you:
<?php
$files = 6;
for($count = 1; $count <= $files; $count++)
require_once"news/news" . sprintf("%02d", $count) . ".php";
?>
<?php
for ($i = 1; $i <= 100; $i++) {
if(!#include("news/news".$i.".php")) {
break;
} else {
include("news/news".$i.".php");
}
}
Something like this
UPDATE
Based on your comment, let's say you have news10 , and you still want pages with 0-based like news01 for single digit numbers (less than 10), so you can add this simple if condition to achieve your need:
<?php
for ($i=10;$i > 0;$i--){
if ($i <10)
$i = "0$i";
include("news/news$i.php");
}
?>
You can use for loop like this:
<?php
for ($i=6;$i > 0;$i--){
include("news/news0$i.php");
}
?>
the index is fixed here, you can read it from a db or an xml file, if you want to maintain the value from outside the script.
<?
for ($i=0; $i<=9; $i++) {
$b=urlencode($cl[1][$i]);
$ara = array("http://anonymouse.org/cgi-bin/anon-www.cgi/", "http%3A%2F%2Fanonymouse.org%2Fcgi-bin%2Fanon-www.cgi%2F");
$degis = array("", "");
$t = str_replace($ara, $degis, $b);
$c="$t";
$base64=base64_encode($t);
$y=urldecode($t);
$u=base64_encode($y);
$qwe = "http://anonymouse.org/cgi-bin/anon-www.cgi/$y";
$ewq = "h.php?y=$u";
$bul = ($qwe);
$degistir = ($ewq);
$a =str_replace($bul, $degistir, $ic);
}
?>
when i put $cl[1][0], $cl[1][1], $cl[1][2] works successfull but when i put $i its returning null. why is this happening?
**I'm trying to change EACH url to base64 codes that I received from remote url with preg_match_all **
Have you checked that $c1[1] has 10 elements? (From $c1[1][0] to $c1[1][9] there are 10 elements, not 9.
Maybe you are getting null for the last one $c1[1][9]. Try to do a var_dump($c1[1]) to check that it contains all the elements that you expect.
Update:
Change the this line
for ($i=0; $i<=9; $i++) {
into this
for ($i=0; $i<9; $i++) {
So I have fields that are generated dynamically in a different page and then their results should posted to story.php page. fields is going to be : *noun1 *noun2 *noun3 and story is going to be : somebody is doing *noun1 etc. What I want to do is to replace *noun1 in the story with the *noun, I have posted from the previous page ( I have *noun1 posted from the previous page ) but the code below is not working :
$fields = $_POST['fields'];
$story = $_POST['story'];
$fieldsArray = split(' ', $fields);
for ($i = 0; $i < count($fieldsArray); $i++) {
${$fieldsArray[$i]} = $_POST[$fieldsArray[$i]];
}
// replace words in story with input
for ($i = 0; $i < count($story); $i++) {
$thisWord = $story[$i];
if ($thisWord[0] == '*')
$story[$i] = ${$thisWord.substring(1)};
}
$tokensArray = split(' ',$tokens);
echo $story;
Your problem is likely that you are trying to echo $story, which I gather is an array. You might have better luck with the following:
$storyString = '';
for ($i = 0; $i < count($story); $i++)
{
$storyString .= $story[i] . ' ';
}
echo $storyString;
echo can't print an array, but you can echo strings to your heart's content.
You almost certainly don't want variable variables (e.g. ${$fieldsArray[$i]}). Also, $thisWord.substring(1) looks like you're trying to invoke a method, but that's not what it does; . is for string concatenation. In PHP, strings aren't objects. Use the substr function to get a substring.
preg_replace_callback can replace all your code, but its use of higher order functions might be too much to get into right now. For example,
function sequence($arr) {
return function() {
static $i=0
$val = $arr[$i++];
$i %= count($arr);
return $val;
}
}
echo preg_replace_callback('/\*\w+/', sequence(array('Dog', 'man')), "*Man bites *dog.");
will produce "Dog bites man." Code sample requires PHP 5.3 for anonymous functions.