Elliot B.
Elliot B.

Reputation: 17651

Cannot use string offset as an array in

I have an array $aMethods whose print_r output is this:

 Array
 (
     [0] => Array
         (
             [pattern] => 
             [return_media] => 1
             [return_name] => 
         )

 )

I'm trying to access 'return_media' with this code:

 $iReturnMedia = $aMethods[0]->return_media;
 echo $iReturnMedia;

Also, when I tried this:

 $iReturnMedia = $aMethods[0]['return_media'];

I get an error stating: Cannot use string offset as an array in...

But it's not working, $iReturnMedia comes back as blank. Could someone tell me what I'm doing wrong here?

EDIT: $aMethods is set in a foreach loop as such:

 foreach ($aMethodList as $sMethodGroup => $aMethods) { //insert code from above }

Upvotes: 0

Views: 178

Answers (5)

Varun Bajaj
Varun Bajaj

Reputation: 1043

find below the code to access the array values -

foreach ($aMethodList as $sMethodGroup => $aMethods) { 
 echo $aMethods[0]['return_media'];
}

Upvotes: 0

Justin John
Justin John

Reputation: 9616

Try this,

$iReturnMedia = $aMethodList[$sMethodGroup][0]['return_media'];
echo $iReturnMedia;

Try to var_dump($aMethods) . It will be give exactly idea of that array...

Upvotes: 0

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

Your accessing it as if it was an object in an array, you do it like:

$iReturnMedia = $aMethods[0]['return_media'];
 echo $iReturnMedia;

Upvotes: 0

FThompson
FThompson

Reputation: 28687

Access the array value by key.

$iReturnMedia = $aMethods[0]['return_media'];
echo $iReturnMedia;

Upvotes: 0

nickb
nickb

Reputation: 59699

You need to use:

$iReturnMedia = $aMethods[0]['return_media'];

The operation -> is for accessing object properties. Since you're just dealing with nested arrays, you need to index them with [].

Upvotes: 3

Related Questions