Array Keys and how do I get them?

Ask about a PHP problem here.
Post Reply
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Array Keys and how do I get them?

Post by Temor »

I have this array setup:
          Array
(
    [cart] => Array
        (
            [0] => Array
                (
                    [item_id] => 1
                    [item_name] => item name
                    [price] => 2
                    [quantity] => 5
                )

            [1] => Array
                (
                    [item_id] => 3
                    [item_name] => another item name
                    [price] => 1
                    [quantity] => 76
                )

            [2] => Array
                (
                    [item_id] => 5
                    [item_name] => yet another item name
                    [price] => 3
                    [quantity] => 9
                )

        )

)
The cart array contains an array for every item inside the cart. What I want is the array key for each item. This is where I'm stuck.

This is probably just me being slow after not writing any code for at least a month, but any guidance is appreciated :)
User avatar
EcazS
Posts: 789
Joined: Fri May 06, 2011 5:29 pm

Re: Array Keys and how do I get them?

Post by EcazS »

http://php.net/manual/en/function.array-keys.php

Maybe?
Not sure if that function works in "multiple dimensions" though, hmm..
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Array Keys and how do I get them?

Post by Temor »

array_keys will return the value of item_id. I want it to go up one level.
User avatar
EcazS
Posts: 789
Joined: Fri May 06, 2011 5:29 pm

Re: Array Keys and how do I get them?

Post by EcazS »

So, if I understand this correctly you want (from your example) 0, 1 and 2?
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Array Keys and how do I get them?

Post by Temor »

yes. precisely
User avatar
EcazS
Posts: 789
Joined: Fri May 06, 2011 5:29 pm

Re: Array Keys and how do I get them?

Post by EcazS »

Well, I suppose if the array will always be called "cart" you could do something like this.
Hopefully I replicated your array correctly,
$array = array(
	"cart"	=> array(
		"0"	=>	array(
			"item_id"	=> "1",
			"item_name"	=> "item name",
			"price"	=> "2",
			"quantity"	=> "5"
		),
		"1"	=>	array(
			"item_id"	=> "3",
			"item_name"	=> "another item name",
			"price"	=> "1",
			"quantity"	=> "76"
		),
		"2"	=>	array(
			"item_id"	=> "5",
			"item_name"	=> "yet another item name",
			"price"	=> "3",
			"quantity"	=> "9"
		)
	)
);

echo "<pre>" . print_r(array_keys($array["cart"]), true) . "</pre>";
This returns an array that looks like this,
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
)
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Array Keys and how do I get them?

Post by Temor »

Works wonders. Thank you :)
Post Reply