2

I'm pretty new to PHP and want to write a "for" statement based on IDs of a page. The problem is that the IDs are not sequential (by that I mean they are not increasing by 1 each time ie. 1,2,3,4,5). Is there a way to use "for" to use specific numbers? For example (pseudocode)

for IDnumbers i = (1,5,7,23,28,34)
 echo "function1(i)"
 echo "function2(i)"
end

I hope that makes sense. I basically want functions associated with each post ID to be returned, but I want the IDnumbers to be specific. Sorry if this is a basic question!

edit: wow, that really was basic. Thanks guys!

1
  • If an answer was helpful, please upvote it; and please accept an answer to mark the question as resolved.
    – poke
    Nov 2, 2011 at 22:25

7 Answers 7

4
// create an array
$numbers = array(1,5,7,23,28,34);

// loop over it
foreach($numbers as $number){
    echo function1($number);
    echo function2($number);
}
3
foreach (array(1,5,7,23,28,34) as $n) {
  echo "function1($n)";
  echo "function2($n)";
}
2
foreach( Array(1,5,7,23,28,34) as $i) {
    // do stuff with $i
}
2

Store the numbers in an array and use a foreach.

2
$IDNumbers = array(1,5,7,23,28,34);
foreach($nums as $num)
{
   echo function1($num);
   echo function2($num);
}

Read more about php foreach here.

2

try something like this:

IDnumbers = array(1,5,7,23,28,34)
 foreach IDnumbers as id
 echo "function1(id)"
 echo "function2(id)"
end
2

IF you MUST use FOR, then you can do this:

$IDNumbers = (1,5,7,23,28,34);

for($i = 0; $i < count($IDNumbers); $i++):
    echo function1($IDNumbers[$i]);
endfor;

This is because even though you stored a number as the value in a numeric array, it still orders it sequentially in reference to the identifiers and where they were added. The value may be 7, but its pointer is 2 (0, 1, 2, 3, 4, 5 in this case)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.