Jump to content
Larry Ullman's Book Forums

Illogical Php? Session And Array Example With $_Get And Foreach


Recommended Posts

Hi Larry and everyone...

 

I was working on a PHP Ecommerce Exercise...

Was using $_GET[new] variable through the url e.g. myexample.php?new=1

I found something that seems to be illogical.... if I use myexample.php?new=1 and then work with $_SESSION['cart'][1]....it works perfectly but if I use myexample.php?new=0672319241 , then $_SESSION['cart'][0672319241] doesn't work as it is expected to, despite of it being used the same way as when new=1.....

 

 

 

To show you what I mean copy and paste the code below to a file called myexample.php and then load it through myexample.php?new=1 and then compare the results to when the results that display when you load it through myexample.php?new=0672319241.....What's the explanation for this?

 

Thank you very much...

 

<?php

 

//

//myexample.php?new=0672319241 versus myexample.php?new=1

//

session_start();

 

 

echo "if you save this file as myexample.php <br/>";

echo "then activate it within ur localhost using a browser by typing myexample.php?new=1 on the url <br/>";

echo "and observe that everything works fine with the myexample.php?new=1 example <br/>";

echo "After that, if you try myexample.php?new=0672319241 <br/>";

echo "You can see that \$_SESSION['cart'][0672319241] doesn't seem to work properly...howcome??? <br/>";

echo "It really seems illogical for it not to work....am I missing something here? <br/> <br/> <br/>";

 

$new = $_GET['new'];

 

if($new){

echo "\$new = ".$new."<br/>";

 

if($new == '0672319241'){

 

$_SESSION['cart'] = array();

$_SESSION['cart'][$new] = "CONTENT_FOR_0672319241";

}else if($new == '1'){

$_SESSION['cart'][$new] = CONTENT_FOR_1;

}

 

 

echo "\$_SESSION['cart'][\$new] = ".$_SESSION['cart'][$new]."<br/>";

 

if($new == '1'){

echo "\$_SESSION['cart'][1] = ".$_SESSION['cart'][1]."<br/>";

}else if($new == '0672319241' ){

 

echo "\$_SESSION['cart'][0672319241] = ".$_SESSION['cart'][0672319241]."<br/>";

}

 

//BUT......

echo "BUT IF YOU USE A FOREACH METHOD TO SEE WHAT's IN THE ARRAY THEN..."."<br/>";

foreach($_SESSION['cart'] as $k => $v){

echo "THIS ARRAY HAS THIS KEY INSIDE = ".$k."<br/>";

echo "THE KEY THEN POINTS TO THIS VALUE = ".$v."<br/>";

 

}

 

 

 

}

 

session_destroy();

 

?>

Link to comment
Share on other sites

Hi HartleySan

 

 

yeah...I could get the values in the super global in one way....but not in the way I expected...but I just realized that I expected it to have a 0, when it did not....

 

anyway...yes...thank you very much :)

Link to comment
Share on other sites

 Share

×
×
  • Create New...