PHP Array Shuffle HTML Links - php

Ok I'm going to try and explain this the best I can, I have 25 links in this format:
bla bla
First thing first, I need to add these 25 links into an array, which I am bit unsure of how to do it because its html, secondly I need to shuffle the array to choose 7 of them randomly and then display those 7.
Hope someone can help, this is beyond me, thanks in advance.
Ok, a little update, I have found a way of getting 1 html link to display randomly, could anyone help me with getting 7 out?
<?php
// Create the array
$links = array();
$links[0] = 'bla1';
$links[1] = 'bla2';
$links[2] = 'bla3';
// Count links
$num = count($links);
// Randomize order
$random = rand(0, $num-1);
// Print random link
echo $links[$random];
?>

For your second task :
Check array_rand() to retrieve X random values in your array.
http://www.php.net/manual/en/function.array-rand.php

If you care only about displaying these links randomized to the user then you can do with JavaScript like this http://jsfiddle.net/hVZL2/.
If you want to load these links into PHP array and do something with them after you still will have to use JavaScript. Convert the array that I created to JSON, send it via POST to some script that will parse JSON and you will have array of links.
As I can see you have your links on server.
<?php
// Create the array
$links = array();
$links[0] = 'bla1';
$links[1] = 'bla2';
$links[2] = 'bla3';
$links[3] = 'bla3';
$links[4] = 'bla3';
$links[5] = 'bla3';
$links[6] = 'bla3';
// Shuffle the array
shuffle($links);
// Display your links, note that we will display five links out of seven
for ($i = 0; $i < 5; $i++){
echo $links[$i];
}

Related

How to randomly select a video and play?

Im learning JQuery and php.
Is it possible to store multiple video links within variables and get php to echo one at random??
My goal is to control my own video ads on my site and I thought this would be a good idea but I dont have a clue where I should look online.
Here is what I was thinking
<?php
$advert1 = 'MyVIDEO1.mp4';
$advert2 = 'MyVideo2.mp4';
$advert3 = 'MyVideo3.mp4';
I want a code that would go here and say: randomly select one of these vars.
echo "At random one of the vars";
?>
I hope Im making sense. help?
You could make an array, like this:
$advert[] = array();
$advert[1] = 'MyVIDEO1.mp4';
$advert[2] = 'MyVIDEO2.mp4';
$advert[3] = 'MyVIDEO3.mp4';
$chosen_one = rand(1,count($advert));
echo $advert[$chosen_one];
You can also use array_rand() instead of shuffle():
<?php
$videos = array("MyVIDEO1.mp4", "MyVideo2.mp4", "MyVideo3.mp4");
echo $videos[array_rand($videos)];
?>
For embedding the video in the right way, have a look at http://www.w3schools.com/html/html_videos.asp
For a start, PHP itself won't exactly play a video. You could use it to echo out one of the URL's to a video. So, bear in mind there is a lot more to do than just select a video.
To answer your question in the code I'd recommend the following:
Try looking up PHP arrays. You want to keep all the videos in an array.
Next up, you'll want to shuffle that array. Then select the first element.
$videos = array("MyVIDEO1.mp4", "MyVideo2.mp4", "MyVideo3.mp4");
shuffle($videos);
echo $videos[0];
This is a simple solution
Place your adverts in an array
<?php
$adverts = array("advert1" => "MyVIDEO1.mp4",
"advert2" => "MyVIDEO2.mp4",
"advert3" => "MyVIDEO3.mp4");
$count = count($adverts);
$rand_advert = rand(1, $count);
echo $adverts['advert'.$rand_advert];
?>
Or alternatively if you don't want to have keys and just put the values in the array straight away
<?php
$adverts = array("MyVIDEO1.mp4",
"MyVIDEO2.mp4",
"MyVIDEO3.mp4");
shuffle($adverts);
echo $adverts[0];
?>
You have need all value in a array then find index randomly and show it.
<?php
$advert = array(
'MyVIDEO1.mp4',
'MyVideo2.mp4',
'MyVideo3.mp4'
);
$total_video = count($advert);
$total_video--; //array index starting from 0 so decrease 1
$random_index = rand(0, $total_video); //array index 0 to 2
$video_to_play = $advert[$random_index];
echo $video_to_play;
?>

Infinite Loop Banner

Excuse me. I am beginner for this code web :)
I have 3 images for my banner...
I dont want appear image banner same as random() statement
I have tried an array multidimensional php
$images[0] = ("1.jpg","2.jpg","3.jpg");
$images[1] = ("2.jpg","3.jpg","1.jpg");
$images[2] = ("3.jpg","1.jpg","2.jpg");
I want to change the position every refresh of my image like $images(array) above
My code like this :
<?php
$a=1;
$i=3;
while($a<=$i){
$images[$a] = ("$appear");}
//$appear is list of image above but I create it with random()
?>
I have 2 question for this problem :
I want to get value where $a=1 and $a=2 images appear as $images[1] = ("2.jpg","3.jpg","1.jpg");and$images[2] = ("3.jpg","1.jpg","2.jpg");
Could I get that value? which code would I use?
I want to use javascript for recall $a=1; if $a had finished (for loop again)....
Could you help me?
I am sorry if My Attitude and My Language is fall apart
I hope you can understand My Idea
Thank you for you greatful ^^
Are you thinking about this.....
for refreshing you have to use session variables
<?php
session_start();
if(!isset($_session['a']))
$_session['a'] = 1;
$a = $_session['a']; // retrieves the value even you refreshes the page
$i=3;
while(1){
$images[$a] = ("$appear");
$a = $a + 1;
if($a>3)
$a=1;
$_session['a'] = $a; //stores the value even you refreshes the page
}
?>
it will reset the $a value to 1 when it reaches 3
If is this you are looking for..?
I think you just have some syntax issues.
Arrays in PHP are in this form:
$images = array('1.jpg', '2.jpg', '3.jpg');
if you want a random image use:
$image = array_rand($images);
Cheers!

Retrieve first 10 comments from .html file

I was goog for hours and just cannot find an answer. Please suggest:
Having a .html file that contains only user comments in paragraphs like:
<p>12/02/2012 4:32pm Mark</p>
<p>Hi! it's a nice demo! Really thankful</p>
<hr>
<p>11/02/2012 11:03am Miron</p>
<p>How to change the font size from CFD again?</p>
<hr>
<!-- AND LOADS OF OTHER <P><P> COMMENTS DELIMITED BY <HR> ... -->
There's 1000's of comments structured like this,
I'd like to grab somehow the newest 10 (not by date, just the first 'ten' comments). And I don't know how.
I know I can use jQuery's .load('comments.html') and than remove all the elements but the first 10 comments, or even include the whole file with PHP and than do the .hide() with jQuery... but it's a good idea to load the whole file for just 10 comments?
How to split that file and get inside an <div id="latest_10_comments"></div> the first 10 comments from the comments.html file?
I know you wanted a JavaScript solution but you could do this in PHP by using the explode function.
Something like this:
$comments = explode("<hr>", file_get_contents("/comments.html"));
for($i = 0; $i < 10; $i++) {
print($comments[$i]);
}
This creates an array called $comments which is each comment in comments.html separated by a
<hr>
tag.
First, I'd suggest reconsidering your approach to this problem entirely. Why are you storing everything an in HTML file this way? You should either store it as an XML file or store it in your database if you want to dynamically load certain comments on demand.
However, to answer your question you're going to need to use an X/HTML parser like PHP's DomDocument if you want to do this in PHP. Here's a working example...
EDIT (changed to reflect the OP's desired behavior):
$dom = new DomDocument;
$dom->loadHTMLFile("comments.html");
// Get all the P tag elements in the DOM
$comments = $dom->getElementsByTagName('p');
// Get only the first 10
$amount = 10; // number of comments you want
foreach ($comments as $num => $comment_nodes) {
if ($num + 1 > $amount)
break;
echo $comment_nodes->nodeValue, PHP_EOL;
}
Solution 1. You can use a RegEx pattern to match 2 p tags followed by hr and repeat the pattern for 10 times.
Solution 2.
Idea from other answer(CHRIS), but as that has error in PHP, I am suggesting this.
$comments = explode("<hr>", file_get_contents("/comments.html"));
for($i = 0; $i < 10; $i++) {
print($comments[$i]);
}
$("<p>").each(function(index, value)
{
//Do what you want here
}
This will cycle through all your <p>. If you know the order of the elements then you can do what you want with them based on index.

Inserting added logic on the fly within a PHP for loop that generates an array

Situation:
I have a front-page slider where users can select from a menu of options which pages they want to include in a front-page slider. The options are stored in a static array and only print the selections of the user up to whatever limit I determine, please see code below.
<?
// Counts the Number of Boxes available for the front page slider
$numberOfBoxes = 6;
$group = array (); // Create an empty array to store all of your final data
//Counts all the checkboxes and their corresponding sliderboxes
for ( $a = 1; $a <= $numberOfBoxes; $a++ )
{
if (${'checkBox_'.$a} == TRUE){
$tempDefaultArray = ${'sliderBox_'.$a};
array_push($group , $tempDefaultArray); // Push the data to the $group array
}
}
$arraySize = sizeof($group); // Find the size of the final array
// Take the outcome from the above calculations and create slider
for ( $i = 0; $i <= ($arraySize - 1); $i++ )
{
$image = $group[$i]['image'];
$title = $group[$i]['title'];
$tagline = $group[$i]['tagline'];
$url = $group[$i]['url'];
$vanityUrl = $group[$i]['vanityUrl'];
print'
<li '.$sliderDivider.'>
<img src="'.$image.'" border="0"/>
<h1>'.$title.'</h1>
<p>'.$tagline.'</p>
<a href="'.$url.'" '.$sliderLink.'/>'.$vanityUrl.'</a>
';}?>
Problem:
This works perfectly, but I want to state that if a particular external variable isset and/or true that the third box in my slider will populate data from a specific object in my array. I would like to maintain the functionality of this existing logic, and just incorporate some extra to override the third box if that variable is set.
Example:
I choose for my slider options to be: Article 1, Article 2, Blog 1, Image 1, and then in a separate area of the customization the user selects YouTube videos. By default when that variable isset, lets call it $youTube then the third selection (in this ex Blog 1) would default to the YouTube. Additional note, this default box lives in the same array as the static options.
This is kind of a tricky thing to explain, and if their are any ninja PHPrs out there that could recommend an efficient way to handle this I would appreciate it.
Hmm, if I understand your question right, you want to have an override within your loop if a certain condition is set outside the array variables?
You can put an if statement in your loop checking the external variable:
if($external_var=="something") {
$image = $static_array['image'];
$title = $static_array['title'];
$tagline = $static_array['tagline'];
$url = $static_array['url'];
$vanityUrl = $static_array['vanityUrl'];
} else {
$image = $group[$i]['image'];
$title = $group[$i]['title'];
$tagline = $group[$i]['tagline'];
$url = $group[$i]['url'];
$vanityUrl = $group[$i]['vanityUrl'];
}

Random Link PHP

EDITED
I'm trying to setup a random link at the bottom of all my pages. I'm using the code below, but want to make it so the current page is not included in the random rotation of links.
Example:
I need code to randomly select and display ONE of these links. The exception being, IF article1.php is currently being viewed, I want it to be excluded from the random selection. That way only links to OTHER articles are seen on any given article.
http://mysite.com/article1.php
http://mysite.com/article2.php
http://mysite.com/article3.php
I would use array_rand with something like:
<?php
$links = array(array('url' => 'http://google.com', 'name'=>'google'),
array('url' => 'http://hotmail.com', 'name' => 'hotmail'),
array('url' => 'http://hawkee.com', 'name' => 'Hawkee'));
$num = array_rand($links);
$item = $links[$num];
printf('%s', $item['url'], $item['name'], $item['name']);
?>
Where links makes it easier to build an array. Nevertheless, I think we miss some details about how you grab your links.
What is the mean of "current page"? because the simplest way to do, is just not add the page to the array.
And the use of array_rand avoids confusion with size of array and so.
Edit: I suppose you use a database, so you may have an sql request like:
SELECT myfieldset FROM `articles` WHERE id = 'theid';
So you know the id of the current article. Now you just have to build an array with some other articles with a query like:
SELECT id FROM `articles` WHERE id NOT IN ('theid') ORDER BY RAND LIMIT 5
And build the candidate array with those results.
Each time you randomly choose a URL to display, pop it off of the array and store it in a temporary variable. Then, on the next rotation make your selection and THEN push the previously used URL back into the array.
$lastUrl = trim(file_get_contents('last_url.txt'));
while($lastUrl == ($randUrl = $urls[rand(0, count($urls) - 1)])){}
file_put_contents('last_url.txt', $randUrl);
// ...
echo $randUrl;
Ensures that on each page load, you will not receive the previous URL. This, however is just an example. You would want to incorporate file locking, exception handling (perhaps) or an entirely different storage medium (DB, etc.)
To ensure the URL is not the same as the current, this should do the trick:
// get current URL
$currentUrl = 'http://' . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
// randomize URLs until you get one that doesn't match the current
while($currentUrl == ($randUrl = $urls[rand(0, count($urls) - 1)])){ }
echo $randUrl;
Google "PHP get current URL", and you'll get considerably more detailed ways to capture the current URL. For example, conditions on whether or not you're use HTTPS, to append an 's' to the protocol component.
try the codes below :
$links = array(
'http://mysite.com/article1.php',
'http://mysite.com/article2.php',
'http://mysite.com/article3.php',
'http://mysite.com/article4.php',
'http://mysite.com/article5.php'
);
$currentPage = basename($_SERVER['SCRIPT_NAME']);
$count = 0;
$currentIndex = NULL;
foreach($links as $link) {
if(strpos($link, "/".$currentPage)>-1) $currentIndex = $count;
$count++;
}
if($currentIndex) {
do{
$random = mt_rand(0, sizeof($links) - 1);
} while($random==$currentIndex);
} else {
$random = mt_rand(0, sizeof($links) - 1);
}
$random_link = $links[$random];

Categories