Create a custom array in PHP - php

I've played around with a personal project regarding a website listing PC games by year of releasing etc. (the topic it is not so important i guess) using the following structure for the links:
http://localhost/
http://localhost/?g=15
http://localhost/?g=30
http://localhost/?g=45
Like it is seen, I've display 15 games per page. What am I working right now is displaying the above links using php in a specific manner for each page (thumbnails, links, etc.):
$arr = array("","?g=15","?g=30","?g=45","?g=60","?g=75","?g=90");
foreach ($arr as $page) {
$link = 'http://localhost/' . (string)$page;
// do stuff to each page link
}
I am very satisfied with how it goes so far but I am wondering if there is a way to create the array automatically not requiring me to manually write the string, just specify the last multiple of 15 for example. I searched the web but I haven't find something concludent or maybe I don't express myself clear enough that's why any help is more than welcomed.

echo 'http://localhost';
for ($i = 15; $i < $max; $i += 15) {
echo "http://localhost/?g=$i";
}
In practice $max is calculated by how many entries there are, which is something you usually figure out from querying a database. Hope this points you in the right direction though.

You can easily generate your array:
<?php
$arr = array('');
$max = 5;
for($i = 0; $i < $max; ++$i) {
$arr[] = '?g='.($i*15);
}
?>

Thry this and tell me if it helps
$links = array();
$links[] = 'http://localhost/';
$multiplier = 5; //the mutiplier, number of links to provide
for ($i = 1; $i < $multiplier; $i++)
{
$links[$i] = 'http://localhost/?g='.(15*$i);
// do here what you want with $links[$i]
}
print_r($links);

Related

PHP: Run through multiple URLs and display their content

Let's say we have an URL looking something like this.
http://domain.com/index.php?p=1&u=A1b2C3d4E5f6G7h8I9j
The number span after ?p= goes from 1 to 999 and the rest is unchanged.
Every URL contains one short line of text.
What would a script look like which can run through all 999 URLs and display their contents?
It would be easy. You can use the FOR LOOP.
<?php
for($i=1; $i < 1000; $i++) {
echo file_get_contents('http://domain.com/index.php?p=' . $i . '&u=A1b2C3d4E5f6G7h8I9j');
}
Documentations:
For Loop
file_get_contents() method
This is going to be resource intensive. But taking a shot in the dark, this should work:
<?php
$urlContent = array();
$urlStart = 'http://domain.com/index.php?p=';
$urlEnd = '&u=A1b2C3d4E5f6G7h8I9j';
$count = 1;
while($count <= 999){
$urlContent[$count] = file_get_contents($urlStart.$count.$urlEnd);
$count++;
}
foreach($urlContent as $content){
echo $content.'\n';
}
?>
This code is Untested

How can I loop through an array, starting at an offset and looping round again?

Newb question: I'm using a foreach loop to get items from an array.
I need to start looping at an offset number- (I'm using a $i variable to do this, no problem).
But when my foreach reaches the end of the array I want it to start going through the array again until it reaches the offset number.
I need to do this so I can have a user open any image in an artist's portfolio and have this image used as the first image presented in a grid of thumbnail icons , with all the other images subsequently populating the rest of the grid.
Any ideas?
Please bear in mind I'm new to PHP! :)
See below for an example of my current code...
$i=0;
$limit=50;// install this in the if conditional with the offset in it (below) to limit the number of thumbnails added to the page.
$offset=$any_arbitrary_link_dependant_integer;
foreach($portfolio_image_array as $k=>$image_obj){//$k = an integer counter, $image_obj = one of the many stored imageObject arrays.
$i++;
if ($i > $offset && $i < $limit) {// ignore all portfolio_array items below the offset number.
if ($img_obj->boolean_test_thing===true) {// OK as a way to test equivalency?
// do something
} else if ($img_obj->boolean_test_thing===false) { // Now add all the non-see_more small thumbnails:
// do something else
} else {
// error handler will go here.
}
} // end of offset conditional
}// end of add boolean_test_thing thumbnails foreach loop.
};// end of add thumbnails loop.
$i = 0;
$limit = 50;
$offset = $any_arbitrary_link_dependant_integer;
$count = count($portfolio_image_array);
foreach($portfolio_image_array as $k=>$image_obj){//$k = an integer counter, $image_obj = one of the many stored imageObject arrays.
$i++;
if ($i > $offset && $i < $limit && $i < ($count - $offset)) {// ignore all portfolio_array items below the offset number.
if ($img_obj->boolean_test_thing===true) {// OK as a way to test equivalency?
// do something
} else if ($img_obj->boolean_test_thing===false) { // Now add all the non-see_more small thumbnails:
// do something else
} else {
// error handler will go here.
}
} // end of offset conditional
}// end of add boolean_test_thing thumbnails foreach loop.
};
Only thing I added was a $count variable.
Edit: If your array starts at 0 I would suggest you put the $i++; at the end of your foreach loop.
A simple method is to use two separate numeric for loops, the first going from offset to end, and the second going from beginning to offset.
<?php
// Create an example array - ignore this line
$example = array(1,2,3,4,5,6);
$offset = 3;
// Standard loop stuff
$count = count($example);
for($i = $offset; $i < $count; $i++)
{
echo $example[$i]."<br />";
}
for($i = 0; $i < $offset; $i++)
{
echo $example[$i]."<br />";
}
?>
This is also almost certainly cheaper than doing multiple checks on every single element in the array, and it expresses exactly what you are trying to do to other programmers who look at this code - including yourself in 2 weeks time.
Edit: depending on the nature of the array, in order to use numeric keys you may first need to do $example = array_values($portfolio_image_array);.
Using Answer Question to force StackOverflow to let me post a decent length of text!
OK #Mark Walet et al, not sure how to post correctly on this forum yet but here goes. I got the issue sorted as follows:
$i=0;
$offset=$image_to_display_number;
$array_length = count($portfolio_image_array);
// FIRST HALF LOOP:
foreach($portfolio_image_array as $k=>$img_obj){// go through array from offset (chosen image) to end.
if ($i >= $offset && $i <= $array_length) {
echo write_thumbnails_fun($type_of_thumbnail, $image_path, $k, $i, $portfolio_image_array, $title, $image_original);
$t_total++;// update thumbnail total count.
}
$i++;
}// end of foreach loop 1.
$looped=true;// Just FYI.
$i=0;// Reset.
// SECOND HALF LOOP:
foreach($portfolio_image_array as $k=>$img_obj){// go through array from beginning to offset.
if ($i < $offset) {
echo write_thumbnails_fun($type_of_thumbnail, $image_path, $k, $i, $portfolio_image_array, $title, $image_original);
}
$i++;
}// end of foreach loop 2.
Thankyou so much for all the help!
:)
as #arkascha suggested use modulo operator
<?php
$example = array(1,2,3,4,5,6);
$count = count($example);
$offset = 3;
for($i = 0; $i < $count; $i++) {
$idx = ($offset + $i) % count
echo $example[$idx]."<br />";
}
?>

Concatanation in php

I have the next situation, lets say i have an object with 10 attributes, named r1, r2, r3...r10. Now i want to extract the value of each attribute dynamically. for that i make a for like this and know it will work
$sum = 0;
for($i = 1; $i <= 10; $i ++){
$key = "r{$i}";
$sum += $this->$key;
}
This is a representative example, what i want to know is if instead of doing that, i could do something like
for($i = 1; $i <= 10; $i ++){
$sum += $this->r{$i};
}
and take the extra line off... i have tried several forms of concatenate this like that but i cant figure it out. Can any one tell me if it is possible and how.
That's because you don't use +=, use .= when concatenating :-)
Have a read of this: http://www.php.net/manual/en/language.operators.string.php
You can do that :
$sum += $this->{'r'.$i};
Having multiples attributes named like that sounds like a problem for me. Why don't you use an array ?

there's any way to use foreach with AND?

foreach(($_POST["msg"] as $mg) AND ($_POST["control"] as $id))
{
echo $mg;
echo $id;
}
i need make something like that, any way to do? i'm trying to get 10 mysql records and edit all of them
No, that won't work. The closest thing I can see to what you're trying to do is:
for($i = 0; $i < count($_POST["msg"]); $i++) {
echo $_POST["msg"][$i];
echo $_POST["control"][$i];
}
Assuming that "msg" and "control" will always contain the same amount of items.
Assuming both $_POST['msg'] and $_POST['control'] are actually arrays, have numeric keys (thanks #iMoses), and have the same length, you could use a for loop -
for ($i = 0; $i < count($_POST["msg"]); $i++){
$mg = $_POST['msg'][$i];
$id = $_POST['control'][$i];
}

Not sure the loop I need to use every two variables

I have a problem where I have an array $user.
I have $_SESSION['players'] which has the total amount of $user.
I need a function where I can take the user1 and 2 and use them. Then move on to user3 and 4 and use them, and so on.. until I have used all the players. Obviously the total $user[$i] would be players-1.
Anyone have a solution for this?
Thanks
Would this suit your needs? This requires that there be an even number of players to work properly though, unless you stick in a check for odd numbers:
for ($i = 0; $i < $_SESSION['players']; $i += 2) {
$userA = $user[$i];
$userB = $user[$i + 1];
// Do things with $userA and $userB variables...
}
just because you're taught how to use for loops in one way does not mean that you're stuck continuing to use them the way you were taught:
$length = count($users);
$length = $_SESSION['players'];
for ($i = 0; $i < $length; $i += 2)
{
if (!isset($user[$i], $user[$i + 1])) break;
$userOne = $user[$i];
$userTwo = $user[$i+1];
//do stuff
}
I realized that isset wasn't necessary, the for call could be modified more:
$length = $_SESSION['players'];
for ($i = 0; ($i + 1) < $length; $i += 2)
{
$userOne = $user[$i];
$userTwo = $user[$i+1];
//do stuff
}
EDIT to change how the length was calculated:
EDIT to validate that user exists
EDIT to add consolidated version

Categories