Tev
Tev

Reputation: 25

PHP: Passing Variables from an include file

I have a script where I'm trying to assign an Array values from an include file (because these same variables will be used in several scripts).

It seems to almost work, but when I try to print the variables, I get a different result:

script.php:

   <?php
    include("test_includes.inc.php");

     $these_numbers = $numbers;
     echo " <pre> print_r($these_numbers)   var_dump($these_numbers)
     </pre>           
     $these_numbers[0]<br>$these_numbers[1]";
    ?>

and test_includes.inc.php

   <?php
   $numbers = ARRAY('one','two');
   ?>

The result:

   print_r(Array)

   var_dump(Array)

   one
   two

I guess I don't understand why the print_r() and var_dump() aren't working and if this is the cause of my problems in my real script (where I do a foreach over each element in the array and run a sql query using it).

Thanks, Tev

Upvotes: 2

Views: 230

Answers (3)

PeeHaa
PeeHaa

Reputation: 72672

PHP doesn't execute function which are in double quotes. It DOES parse variables though (hence the ARRAY).

So:

$test = 'something';

echo "$test"; // outputs something

echo "strtoupper($test)"; // outputs strtoupper(something) instead of SOMETHING

In you specific case you can do:

<?php
include("test_includes.inc.php");

$these_numbers = $numbers; // not really needed, but hard to tell without seeing your complete code
echo "<pre>";var_dump($these_numbers);echo "</pre>";

Upvotes: 2

Jonathan Rich
Jonathan Rich

Reputation: 1738

PHP doesn't interpolate function calls - it's literally outputting print_r(, then $numbers, then )

What you want to do is this:

echo " <pre> " .
     print_r($these_numbers) .  
     var_dump($these_numbers) .
     "</pre>" .        
     "$these_numbers[0]<br>$these_numbers[1]";

Upvotes: 1

Naftali
Naftali

Reputation: 146302

Thats because thouse functions don't work in quotes:

echo "<pre>".
     print_r($these_numbers) .
     var_dump($these_numbers) .
     "</pre>" .           
     "$these_numbers[0]<br>$these_numbers[1]";

Upvotes: 0

Related Questions