tags:

views:

75

answers:

6

is it possible to use values that are obtained within a loop/function out side the loop/function where it is used or called?

below is my function

function off($limit)
{
    $string=file_get_contents("feed.xml");
    $xml=simplexml_load_string($string);

    foreach ($xml->FOUND->CAT as $place)
    {
        $limits = $place->CORDS;
        $rate=$place->STARS;
        $phone=$place->PHONE;
    }
}

Im calling it to a php file which has html tags. Is it possible to get the values that are returned by the function into the rows that are marked by XXXX to display ?

<html>
<body>
<?php
off(‘57854’);
?>
<table width="200" border="1">
  <tr>
    <td>XXXXX</td>
    <td>XXXXX</td>
    <td>XXXXX</td>
  </tr>
  <tr>
    <td>XXXXX</td>
    <td>XXXXX</td>
    <td>XXXXX</td>
  </tr>
  <tr>
    <td>XXXXX</td>
    <td>XXXXX</td>
    <td>XXXXX</td>
  </tr>
</table>
</body>
</html>

I would like to know is there a way to display without including the html tags within the function.

Any help will be appreciated.

Thanks

+2  A: 

you put a return statement in your function. then you can use it "outside"

ghostdog74
A: 

Not without making each of the function variables global

function func() {
  global $var1, $var2, ...;
  ...
}
?>
<td><?=$var1?></td>

Note: for the above to work, short tags must be enabled, otherwise you have to do <?php echo $var1 ?>

Tor Valamo
A: 

You need to return the value out of the function:

function foo() {
  return array("bar");
}

Any time I call foo(), I'll be able to catch it's return value:

$items = foo(); // $items is now array("bar");

foreach($items as $item) {
  print "<td>" . $item . "</td>"; // <td>bar</td>
}
Jonathan Sampson
A: 

There are three ways:

1., Either you save result of each loop turnaround into an array and then loop through array

<table>
<?php foreach ($array as $a){
echo "<tr><td>$a</td></tr>";
} ?>
</table>

2., or you echo each row through the loop (in that off function)

3., or you start a buffer with ob_start and then save it to some variable ($result = ob_get_contents())

Either way, you'll need more loops and some echos.

Adam Kiss
+2  A: 

Yes, you can get the result of a function and use it outside. Example:

function addSomething($a, $b)
{
    $sum = $a + $b;
    return $sum;
}

$mySum = addSomething(15, 45);

print $mySum;  // Will show 60

You can only 'return' one variable as it will 'exit' the function once you return. If you need more data than just a single variable you can return an array and pick that up on the other side.

angryCodeMonkey
+2  A: 
Tatu Ulmanen
Why the downvote? This is exactly what the OP asked for, with an clear example.
Tatu Ulmanen
Thank you very much :D
LiveEn