title: PHP - How do I make a function wait and return another functions value
body: <p>So I have some XML I need to loop through children to find a childs value. The problem is the actual looping. The way I know of is making a function, and if there is a child, use the same function and loop through the children - and again and so fourth.</p>
  
  <p>My problem is that it doesn't seem as if the function is waiting for the "child function" to finish before returning my value.</p>
  
  <p>Is there a better way of doing this? I know there are callbacks but I'm unsure how I would implement it here</p>
  
  <p><strong>Example XML</strong></p>
  
  <pre><code>&lt;?xml version="1.0" standalone="yes"?&gt;
  &lt;pages&gt;
      &lt;page&gt;
          &lt;title&gt;Parent Page1&lt;/title&gt;
          &lt;id&gt;0&lt;/id&gt;
          &lt;children&gt;
              &lt;page&gt;
                  &lt;title&gt;Child Page1&lt;/title&gt;
                  &lt;id&gt;1&lt;/id&gt;
                  &lt;children/&gt;
              &lt;/page&gt;
          &lt;/children&gt;
      &lt;/page&gt;
      &lt;page&gt;
          &lt;title&gt;Parent Page2&lt;/title&gt;
          &lt;id&gt;2&lt;/id&gt;
          &lt;children&gt;
              &lt;page&gt;
                  &lt;title&gt;Child Page2&lt;/title&gt;
                  &lt;id&gt;3&lt;/id&gt;
                  &lt;children/&gt;
              &lt;/page&gt;
          &lt;/children&gt;
      &lt;/page&gt;
  &lt;/pages&gt;
  </code></pre>
  
  <p><strong>Example PHP</strong></p>
  
  <pre><code>$page = "Child Page2";
  echo "The ID of " . $page . " is " . a($page);
  
  function a ($title) {
      $xml = simplexml_load_file("pages.xml") or die("Failed.");
      return b ($xml[0], $title);
  }
  
  function b ($pages, $title) {
      $val;
      foreach ($pages as $page) {
          if($page-&gt;title == $title) {
              $val = $page-&gt;id;
              break;
          } else if ($page-&gt;children-&gt;children() &gt; 0){
              $val = b($page-&gt;children-&gt;children(), $title);
          }
      }
      return $val;
  }
  </code></pre>
  
  <p>Is outputting: <code>The ID of Child Page2 is</code></p>
  
  <p>Now I know the XML isn't perfect in this example but it's only a placeholder so you understand what I'm trying to do. I'm using SimpleXML on the XML if that helps in any way</p>
  
  <p><strong>Solution</strong></p>
  
  <p>The problem was that if <code>b();</code> returned in the first branch, but still needed to check other branches of children, the whole thing returned <code>null</code> or simply nothing at all.</p>
  
  <p>My solution lower down works, but went with Swayze's answer because it's shorter and more effective (Saves saving variables)</p>