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.
Related
So the loop isn't printing and I don't understand why? I'm only a beginner so I'm really confused on why it won't work. If you guys could explain the reason behind it too that would be great.
<html>
<body>
<?php
$numbers = array(4,6,2,22,11);
sort($numbers);
function printarray($numbers, $x) {
$countarray = count($numbers);
for($x = 0; $x < $countarray; $x++) {
echo $numbers[$x];
echo "<br>";
}
}
printarray();
?>
</body>
</html>
You need to add your variable to your function:
printarray($numbers);
You can also remove the $x from the function as it is being created and destroyed in the function itself.
Since you are a beginner, you might be interested in learning about foreach. You can use it to greatly simplify your function like so:
<?php
$numbers = array(4,6,2,22,11);
sort($numbers);
function printArray($nums) {
foreach($nums as $num) {
echo $num;
echo "<br>";
}
}
printArray($numbers);
Experiment via: https://3v4l.org/1BtkK
Once you get used to using foreach, take a look at array_map, array_filter, and array_reduce as ways to simplify your code even more.
<?php
$numbers = array(4,6,2,22,11);
$sort($numbers);
function printArray($nums) {
array_reduce($nums, function ($carry, $item) {
echo $carry .= $item . "<br>";
});
}
printArray($numbers);
Experiment via: https://3v4l.org/4JJFL
And since you are a beginner, check out PHP The Right Way and practice. Once you have gained experience, check out PHP The Right Way again and practice some more. And again. And again.
I'm using json_decode to parse JSON files. In a for loop, I attempt to capture specific cases in the JSON in which one element or another exist. I've implemented a function that seems to fit my needs, but I find that I need to use two for loops to get it to catch both of my cases.
I would rather use a single loop, if that's possible, but I'm stuck on how to get both cases caught in a single pass. Here's a mockup of what I would like the result to look like:
<?php
function extract($thisfile){
$test = implode("", file($thisfile));
$obj = json_decode($test, true);
for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) {
//this is sometimes found 2nd
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring1") {
}
//this is sometimes found 1st
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring2") {
}
}
}
?>
Can anyone tell me how I could catch both cases outlined above within a single iteration?
I clearly could not do something like
if ($obj['patcher']['boxes'][$i]['box']['name'] == "string1" && $obj['patcher']['boxes'][$i]['box']['name'] == "string2") {}
...because that condition would never be met.
Generally what I do when I have raw data that is in an order that isn't ideal to work with is to run a first loop pass to generate a a list of indexes for me to pass through a second time.
So a quick example from your code:
<?php
function extract($thisfile){
$test = implode("", file($thisfile));
$obj = json_decode($test, true);
$index_mystring2 = array(); //Your list of indexes for the second condition
//1st loop.
$box_name;
for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) {
$box_name = $obj['patcher']['boxes'][$i]['box']['name'];
if ( $box_name == "mystring1") {
//Do your code here for condition 1
}
if ($box_name == "mystring2") {
//We push the index onto an array for a later loop.
array_push($index_mystring2, $i);
}
}
//2nd loop
for($j=0; $j<=sizeof($index_mystring2); $j++) {
//Your code here. do note that $obj['patcher']['boxes'][$j]
// will refer you to the data in your decoded json tree
}
}
?>
Granted you can do this in more generic ways so it's cleaner (ie, generate both the first and second conditions into indexes) but i think you get the idea :)
I found that something like what #Jon had mentioned is probably the best way to attack this problem, for me at least:
<?php
function extract($thisfile){
$test = implode("", file($thisfile));
$obj = json_decode($test, true);
$found1 = $found2 = false;
for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) {
//this is sometimes found 2nd
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring1") {
$found1 = true;
}
//this is sometimes found 1st
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring2") {
$found2 = true;
}
if ($found1 && $found2){
break;
}
}
}
?>
Here is my code :
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b-1);$i++)
{
for($j=1;$j<($b);$j++)
{
if($a[$j]<$a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
I just want to know what's wrong in the above code ? because if i take 3 array values it works fine but for 4 its not working....can someone do the modification for the same code,and also please briefly explain why is it not working any issues with looping?I am not looking for different code.
You have mistakenly modified the bubble sort algorithm. Use standard one.
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++) //Changes over here
{
for($j=0;$j<($b);$j++) //Changes over here
{
if($a[$j]>$a[$i]) //Changes over here
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
Why are you manually sorting when you have sort?
$a = array(10,8,6,5);
sort($a);
var_dump($a);
Similarly, why are you using temporary variables when you have list?
list($a[$i],$a[$j]) = array($a[$j],$a[$i]);
try below code may be that will help.
<?php
function pr($array = array())
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$a = array(10,8,6,5);
$b = count($a);
for($i=0;$i <= ($b-1);$i++)
{
for($j=0; $j < ($b);$j++)
{
if($a[$j] < $a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
pr($temp);
pr($a);
?>
<?php
$a=array(8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++)
{
for($j=0;$j<($b);$j++)
{
if($a[$j]<$a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
The inner loop doesn't need to be executed n times (where n=number of elements to be sorted). Every time the outer loop executes, one more element at the end (for ascending order) is in the correct position. So, inner loop should not check those elements.
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++){
for($j=0;$j<($b-$i);$j++){ // this change will save time
if($a[$j]>$a[$i]){
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
?>
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);
}
I have programmed a script with the goto command but on the server where I want to execute the script there is a previous PHP version (<5.3), so I have to change the code. The structure of the code goes like that:
for($i = 0; $i < 30; $i++) // print 30 articles
{
$x = 0;
// choose a a feed from the db
// parse it
a:
foreach($feed->get_items($x, 1) as $item)
{
// create a unique id for the article of the feed
if($id == $dbid)
{
// if this id exists in the db, take the next article of the same feed which is not in the db
$x++;
goto a;
}
else
{
// print the original article you grabbed
}
} // end of foreach
} // end of for
I have tested everything. Do you have any ideas how can I retransform this code without goto in order to be executed properly???
This questions demonstrates why goto should be avoided. It lets you get away without thinking about the algorithm enough.
The standard way to do this is with a flag. I hope you were not expecting a "herezthecode kthxbai" sort of an answer, but in this case the best way to explain it would be to write the code -
for($i=0;$i<30;$++){
$x=0;
do {
$found = false;
foreach($feed->get_items($x,1) as $item){
// get $id
if($id==$dbid){
$found = true;
break;
}else{
// other things
}
}
$x++;
} while($found);
}
Without knowing how the ->get_items() call behaves you could use this brute-force method in lieu of the goto-switch:
for($i = 0; $i < 30; $i++)
{
$x = 0;
$a = 1;
while ($a--)
foreach($feed->get_items($x, 1) as $item)
{
if($id == $dbid)
{
$x++;
$a=1; break;
}
else
{
}
} // end of foreach
} // end of for
The label gets replaced by a while and a self-fulfulling stop condition. And the goto becomes a break and resets the $a stop condition.
Something like this would probably work...
function loop(){
foreach($feed->get_items($x,1) as $item){
if($id==$dbid){
$x++;
loop();
}else{
}
}
}
for($i=0;$i<30;$++){
$x=0;
loop();
}
I'm sorry, I removed all the comments, they were annoying.
Move the declaration of $x outside of the for loop and replace your label/goto combination with a break, like so...
$x=0;
for($i=0;$i<30;$++) //print 30 articles
{
foreach($feed->get_items($x,1) as $item)
{
// create a unique id for the article of the feed
if($id==$dbid)
{
//if this id exists in the db,take the next article of the same feed which is not in the db
$x++;
continue;
}
else
{
//print the original article you grabbed
}
} // end of foreach
}//end of for
Agree with unset - using break will break if loop and keep iterating through for loop