-2
stdClass Object 
( 
    [string] => Array 
    ( 
        [0] => EXL 
        [1] => TEMPS 
    ) 
)


stdClass Object 
( 
   [string] => IP
) 

How to access to EXL, TEMPS and IP values with a loop for ?

2 Answers2

1

You have to access the parent array as Object, but the child's are normal array.

SO try this.

$array->string[0];  //get the EXL 

Example:

$array = array(
    "string" => array("EXL", "TEMPS"),
    "string2" => array("EXL 2", "TEMPS 2"),
);

$obj_arr = (Object) $array;
echo "<pre>";
print_r($obj_arr);
echo "</pre>";

echo $obj_arr->string[0]."<br/>".$obj_arr->string[1];

Output:

EXL
TEMPS

Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
0

In your case, this is an instance of a Class which gives you an Object.

There are two commonly used methods to target an Array within an Object:

// Loop through each stored data
foreach($Object->string as $_string)
{
    echo $_string;
}

Or you can access the Array directly:

echo $Object->string[0];

The -> in PHP is how we use Objects (map).

Both work fine.

EDIT: Reading comments

To access the Array held in the Object within a for loop:

// $i starts at 0 since array index's start at 0
for($i = 0; $i < count($Obj->string); $i++)
{
    echo $Obj->string[$i];
    // TODO: Add your code...
}
Jaquarh
  • 6,493
  • 7
  • 34
  • 86
  • `echo $Object->string->{0}; // Just looks cleaner (IMO)` wrong 0 is an array index not a property. `echo $Obj->string->{$i};` same as before it's an array index. – Rizier123 Mar 30 '16 at 10:04
  • He didn't state any of what you're saying above, if it hassles you, edit it. – Jaquarh Mar 30 '16 at 10:08
  • OP doesn't have to state that if everything is in the output. *if it hassles me* , you posted an answer here and I just point out what is technical incorrect at your answer. – Rizier123 Mar 30 '16 at 10:10