Page 1 of 1

PHP with Javascript, Array not getting updated

Posted: Thu Nov 06, 2008 8:14 pm
by ChipChamp
Here is the header of my page (I am mixing a bit of javascript with php, but it seems like the problem is with the php part):

Code: Select all

<script type="text/javascript">
function start() {
 
<?php
$slot = array(0,0,0,0,0,0);
?>
}
 
function drop() {
<?php
$i = 0;
for ($i = 0; $i < 6; $i ++) {
if ($slot[$i] == 0) {
$slot[$i] = 1;
?>
document.getElementById("s"+<?php echo $i ?>).innerHTML="This";
<?php
break;
}
}
?>
}
 
</script>
The problem is that once it runs through the drop() function, it works fine, but when the function ends it sets the $slot array back to 0,0,0,0,0,0. Is there any reason why this would be happenng? Any help would be helpful.. Thanks!

Re: PHP with Javascript, Array not getting updated

Posted: Thu Nov 06, 2008 8:36 pm
by Stryks
You can't mix javascript and PHP. They are totally different monsters.

PHP happens on the server, before the page is sent to the user. Javascript only happens after the page arrives at the user, it plays no part on the server itself.

That's not to say that they cant be used together, by having PHP produce custom javascript for a page, or by using AJAX to pass data between the active page (user side) and the server.

But as for how you are using that .. well .. if you look at the page in your browser and 'view page source', you'll likley see that none of the PHP code exists in the javascript anymore. PHP parsed it on the server, and as none of it outputs anything, nothing was output.

Hope that clarifies things somewhat.

Re: PHP with Javascript, Array not getting updated

Posted: Fri Nov 07, 2008 1:34 am
by oddsmojo
You defined $slot with array(0,0,0,0,0,0) in the main section of your code. Inside the function, you gave it a new value. The variable $slot will have its own scope depending on where it's value is defined. (example)

Code: Select all

<?
 
 [color=#66AAAA]$scope = "outside";[/color]
 test();
 
 function test()
 {
  [color=#AA66AA]$scope = "inside";[/color]
  echo $scope ," --> ";
 }
 
 echo $scope;
 
 // [color=#AA66AA]inside [/color]--> [color=#66AAAA]outside[/color]
 
?>
You can change the scope if you want by declaring it as a global inside of the function. Any changes made here will update the $slot outside of the function. (EX)

Code: Select all

<?
 
 $scope = "outside";
 test();
 
 function test()
 {
 
[color=#FF0000]  global $scope;[/color]
 
  $scope = "inside";
  echo $scope ," --> ";
 }
 
 echo $scope;
 
 //inside --> inside
 
?>

Hope this helps!