PHP - Selecting random strings/variables to echo from a file
what I am trying to achieve here is echoing a list of 5 links, the links are created from keywords within a file being comma seperated (keyword1, keyword2). The file contains 20 keywords and I'm wanting to randomly grab 5 to display on each page load.
The issue I am currently experiencing is that all the keywords are being echoed out rather than just the 5. This is what I have:
<?php
$keywords=file_get_contents("keywordlist.php");
$keyword_list = explode("\n",$keywords);
shuffle($keyword_list);
$display = 5;
if((count($keyword_list) - 1) > ($display - 1))
{
开发者_高级运维 $show = $display - 1;
}
else
{
$show = count($keyword_list) - 1;
}
for ($i=0; $i<=$show; $i++)
{
$page_name = $keyword_list[$i];
$clean_list = str_replace(" ","-",$page_name);
$output .= '<a href="/'.$clean_list.'">'.$page_name.'</a>, ';
}
echo $output;
?>
Any help would be much appreciated thank you :)
<?php
$keywords = explode(",", file_get_contents("keywordlist.php"));
shuffle($keywords);
$links = array();
foreach (array_slice($keywords, 0, 5) as $word) {
$word = trim($word);
$slug = str_replace(" ", "-", $word);
$links[] = '<a href="/' . $slug . '">' . $word . '</a>';
}
echo join(',', $links);
You say
within a file being comma seperated
then in your code you
$keyword_list = explode("\n",$keywords);
So if your keywords are separated by commas, change your code to
$keyword_list = explode(",",$keywords);
otherwise change your input file.
精彩评论