tags:

views:

69

answers:

2

All,

I have an array with hyphens in the key name. How do I extract the value of it in PHP? It returns a 0 to me, if I access like this:

print $testarray->test-key;

This is how the array looks like

 testarray[] = {["test-key"]=2,["hotlink"]=1}

Thanks

+2  A: 

print $testarray["test-key"];

The PHP manual has a good page explaining arrays and how to do things with them: http://www.php.net/manual/en/language.types.array.php

Scott Saunders
+5  A: 

You have problems:

testarray[] = {["test-key"]=2,["hotlink"]=1}
    1                        2
  1. You are missing $ used to create variables in php
  2. It is not a valid array format

.

print $testarray->test-key;
               1
  1. The => operator is used for objects, not arrays, use [] instead.

Here is how your code should be like:

$testarray = array("test-key" => 2, "hotlink" => 1);
print $testarray['test-key'];

Finally,

See PHP Array Manual

Web Logic
What if I want to access it as an Object?
Vincent
You can not access an array as an object
Scott Saunders
@Vincent: Why do you want to read it as object in the first place, there is no need, any ways you should first convert array to object as shown here: http://www.lost-in-code.com/programming/php-code/php-array-to-object/
Web Logic
please refer to:http://stackoverflow.com/questions/2925044/hyphens-in-keys-of-object
Vincent
@Vincent: It looks to be an object too, if it works for you anyway, you can go for that :)
Web Logic