2

I have an array of ids, and for each id, I want to include a file, and send the id to the include-file, but after the first id, the other ids are empty. Why are the other ids not passed through the include-file?

    $ids = array(1, 2, 3);
    foreach($ids as $id) {
         $id = $id;
         include_once("file.php");
         echo $path . "<br />"; // comes from include-file
    }

When I echo my $id in the include-file, I get '1', but the other two ids are empty?

5
  • 1
    Return will exit loop Commented Nov 13, 2015 at 13:43
  • 2
    Yoy dont need to redeclare $id since it exists. So use only the include in your loop delete/comment de return and id line Commented Nov 13, 2015 at 13:45
  • I'm sorry, It's echo, i changed this Commented Nov 13, 2015 at 13:45
  • 1
    So if I understood correctly your file.php is the same for each id. Than use include instead of include once. Include once will only fire once Commented Nov 13, 2015 at 13:48
  • also one more thing, suppose you have N ids, it's a really bad thing to include one file N times. instead include once a type of functions file and run a specific function which will return the $path you are seeking, and !important do this outside of the loop. Commented Nov 13, 2015 at 14:03

1 Answer 1

3

You have this problem, because you are using inlcude_once, this makes exactly what the name suggests, it is including your file only once.

You need include. By the way, you can drop $id=$id;, because you have $id already defined in the foreach here: foreach( $ids as $id ).

Try this instead:

$ids = array( 1, 2, 3 );
foreach( $ids as $id ) {
    include( "file.php" );
    echo $path . "<br />"; // comes from include-file
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! In the include-file, I declared a function, why is this a problem? Because when I remove the function, I get each id.
This is because in your example the function would be declared 3 times due to the 3 `include? in the foreach, you can declare a function only once in php.
@swidmann this comment saved me hours of headache; I was doing the same thing as OP and didn't realize that my loop with include wasn't working because I had declared functions in the include. Thanks!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.