I have both PHP and HTML in one file, following the pattern:
-HTML1
-PHP1
-HTML2
<-script>
-PHP2
<-/script>
-rest of HTML
In the PHP2 section, I call a function in PHP1 which returns an array.
I can get a value for count($arr)
, but I cannot print the values in the array. It simply shows as an empty string when I examine the source code in the browser.
When I copy the statements in the function from PHP1 to PHP2, everything works - I can print the values of the array.
Code follows:
<?
include('pathdata.php');
function getThePath($node1, $node2){ //pass strings
$n1 = $matchIDtoNum[$node1]; //get int (from pathdata)
$n2 = $matchIDtoNum[$node2];
$res = array();
$res[0] = $n1;
$res[1] = $n2;
return $res;
}
$node1='';
$node2='';
if($_GET["node1"]){
$node1 = $_GET["node1"];
}
if($_GET["node2"]){
$node2 = $_GET["node2"];
}
if ($node1!='' && $node2!=''){
$arr = getThePath($node1,$node2);
}
?>
<html>
<head><title>Paths</title>
<script>
function init(){
<?
echo ("document.getElementById('msg1').innerHTML = 'test';\n");
if($node1!='' && $node2!=''){
//$n1 = $matchIDtoNum[$node1];
//$n2 = $matchIDtoNum[$node2];
//$res = array();
//$res[0] = $n1;
//$res[1] = $n2;
//$arr=$res;
$num = count($arr);
$str = implode(' ', $arr);
echo ("document.getElementById('msg1').innerHTML = '$arr[0]';\n"); //Empty string
echo ("document.getElementById('msg2').innerHTML = '$str';\n"); //String with one space character
echo ("document.getElementById('msg3').innerHTML = '$num'+' '+'$node1'+' '+'$node2';\n"); //this always works
}
?>
}
</script>
</head>
<body onload="init()">
<h1>Given two Nodes, return Shortest Path</h1>
<form name="inputform" action="getpath.php" method="get">
<input type="text" name="node1" />
<input type="text" name="node2" />
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
<br/>
<p id ="msg1"></p>
<p id ="msg2"></p>
<p id ="msg3"></p>
<br/>
</form>
</body>
</html>
Any advice on where I might be going wrong?
Thanks!
Edited to Add: What worked for me was putting global $matchIDtoNum;
inside the function. i.e.
function getThePath($node1,$node2){
global $matchIDtoNum;
$n1 = $matchIDtoNum[$nd1];
//etc
}
This gave the expected output for me.
Thanks to all the commenters and answerers!
$matchIDtoNum
Your functon works correctly. http://codepad.org/ZcbXMDyd What is the purpose of$matchIDtoNum[]
? – Davinder Jul 25 '12 at 4:55