Arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dubs
Forum Commoner
Posts: 28
Joined: Tue Oct 12, 2004 4:55 pm

Arrays

Post by dubs »

Code: Select all

<?php
<?php  
session_start();
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
//set new product flag to zero
$new = 0;

//Conver URL variable to normal variables
$Product = $_GET['Product'];
$Qty = $_GET['Qty'];
$Price = $_GET['Price'];

//Is there a cart and if not create one
if(!isset($_SESSION['cart']))
{					
	$_SESSION ['cart'][] = array();    
	$_SESSION ['items'] = 0;
	$_SESSION ['Total Price']= 0.00;
}

//Has the Array been initialised if it has...
if(isset($_SESSION ['cart'])){
	foreach($_SESSION ['cart'] as $key){		
		foreach( $key as $element){
			echo $element . '<br>';
			if($element[0] == $Product){
			// If the product exists then we need to update the quantity
				$_SESSION ['cart'][$key][1] = + $Qty;		
				}
			else{
				// if the product isn't in the basket
					$new = 1;
				}
		}
	}
}
if($new == 1){
	//if the add new variable is 1 then append another array to cart
	$_SESSION ['cart'][] = array($Product,$Qty,$Price); 
}		
//Debug
echo '<pre>';
print_r($_SESSION ['cart']);
echo '</pre>';
?>

?>
I'm trying to build a php shopping cart and my practice application seems to be failing here:

Code: Select all

echo $element . '&lt;br&gt;';
			if($element&#1111;0] == $Product)&#123;
If i out output $element without an index or key then it simply loops over the values for each of elements. If i specify and an index for example $element[0] the it only outputs the first character in the string.

How do i access the value of $element[0]
?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

$element is a string, so $element[0] is the first character of said string.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Re: Arrays

Post by timvw »

[quote="dubs"]

Code: Select all

$_SESSION ['cart'][] = array();    
$_SESSION ['items'] = 0;
$_SESSION ['Total Price']= 0.00;

//Has the Array been initialised if it has...
if(isset($_SESSION ['cart'])){
	foreach($_SESSION ['cart'] as $key){		
		foreach( $key as $element){
			echo $element . '<br>';
			if($element[0] == $Product)
you loop over the cart elements (actually, you are getting the values, which makes $key a weird name for that usage :))

And then for each of those values, you try to loop over the elements.

Because those values are strings, you get the characters...
dubs
Forum Commoner
Posts: 28
Joined: Tue Oct 12, 2004 4:55 pm

Post by dubs »

ahhh i see...cheers 8O
Post Reply