Reputation: 2014
class myClass {
public $user=array(
'first_name' => 'Andi',
'last_name' => 'Abdulloh',
'result' => array('A','B','C','D','E'));
}
$db=new myClass();
i call first_name
by doing $db->user[first_name]
, but i cant figure out how to get the value of result
inside that class. when i try to do $db->user[result[0]]
it returns an error.
Upvotes: 1
Views: 3673
Reputation: 81384
Use
$db->user['result'][0]
By the way, array keys that aren't quoted strings are generally bad practice (and throw a warning or notice, I can't remember which). So, when you access the first name, use this instead:
$db->user['first_name']
Why? Off to the PHP documentation:
This [using array keys unquoted] is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.
In addition, there is a performance degradation if you don't quote your array keys; PHP must lookup the token in the constants table, then, realising it isn't defined, replace it with its equivalent string.
Upvotes: 0
Reputation: 401002
You should use :
$db->user['result'][0]
[]
allow you to access elements of an array :
$db->user
is an array, indexed with named-keys ; so you use $db->user['name of the key']
to access its sub-elements$db->user['result']
is also an array, but indexed by integers ; so you use $db->user['result'][1]
to access its elements
And, as an important sidenote : your should not use $db->user[first_name]
: you should use $db->user['first_name']
-- note the quotes arround the name of the item.
For more informations, see my answer to this question : Is it okay to use array[key] in PHP?
Upvotes: 3