Arrays Values

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
User avatar
phpcoder
Forum Contributor
Posts: 158
Joined: Sat Nov 02, 2002 1:18 pm
Location: Manchester, UK

Arrays Values

Post by phpcoder »

HI,

I cant acces values of arrays. Anything wrong with my code.

Code: Select all

<?php
class ordClass
{
public $Item;
}

$obj = new ordClass;



$obj->Item[]= array ( 'Sku' => "Test1", 'Description' => "Test1");


for ($i=0; $i < count($obj->Item); $i++)
	{
		print "SKU".$obj->Item[Sku];
		print "<br>";
	}
	
	?>
Hemlata
Forum Commoner
Posts: 35
Joined: Mon Sep 10, 2007 5:40 am
Location: India
Contact:

Post by Hemlata »

Hello,

I think you are using wrong way for assigning values to variable '$obj->Item'.

If you modify your code to as follows, you will be getting array values.

Code: Select all

<?php

class ordClass
{
	public $Item;
}

$obj = new ordClass;
$obj->Item= array ( 'Sku' => "Test1", 'Description' => "Test1");

for ($i=0; $i < count($obj->Item); $i++)
{
	print "SKU".$obj->Item[Sku];
	print "<br>";
}
?>
Hope this might solve your issue.

Regards,
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Without going into details about some other issues I see with your script, heres my suggestions
  • $this->Item is set to public, I would probably make this a private property and create a method to set and retrieve your orders list
  • count() within a loop is not efficient, storing the count() in a variable and using the variable in the loop is better
  • As suggested earlier, $obj->Item should store an array of arrays, not simply a single dimensional arrays.
  • You are still not accessing the properties correctly. Using a for() loop, you should access the indice you are currently looping:

    Code: Select all

    print "SKU". $obj->Item[$i]['Sku'];
  • I would probably use a foreach() anyway, and rid myself of the count() call all together

    Code: Select all

    foreach ($obj->Item as $item) 
    {
       echo $item['Sku'] .'<br>';
    }
  • Always quote your array indices, $item[Sku] will fire a php notice
Post Reply