tadalendas
tadalendas

Reputation: 1541

How to get a value of an element in a PHP array

How do I reference the price in the last branch?

I have tried $arr['lines']['line1']['price'], but I got an error. What is the correct way o referencing?

 array (size=100)
0 => 
array (size=34)
  'id' => string '1' (length=1)
  'invoicenr_full' => string 'dsf' (length=7)
  'invoicenr' => string 'fsd' (length=7)
  'reference' => 
    array (size=3)
      'line1' => string 'fsde' (length=20)
      'line2' => string 'sfsdfd' (length=31)
      'line3' => string 'dfsds' (length=45)
  'lines' => 
    array (size=1)
      'line1' => 
        array (size=7)
          'amount' => string '1' (length=1)
          'amount_desc' => string '' (length=0)
          'description' => string 'sdfsdf'
          'tax_rate' => string '21' (length=2)
          'price' => string '150' (length=3)
          'discount_pct' => int 0
          'linetotal' => int 150

Upvotes: 0

Views: 43

Answers (3)

Nirnae
Nirnae

Reputation: 1345

To access your element, you could to the following :

$price = $arr[0]['lines']['line1']['price'];

Also if your first level "[0]" is useless you could use array_shift($arr);

Then you would access your elem like this :

$price = $arr['lines']['line1']['price'];

Upvotes: 1

Vistari
Vistari

Reputation: 707

If you don't want to use the zero index you can also use array_shift

$theArray = array_shift($theArray);

This will allow you to access any array element and you don't have to use the first element "[0]" key like so:

$theArray['lines']['line1']['price']

Upvotes: 0

William_Wilson
William_Wilson

Reputation: 1264

If this is an accurate description of the structure: $arr[0]['lines']['line1']['price']

where 0 is the index of the first level.

Upvotes: 3

Related Questions