How to access the property / value of an array that has been converted to an object?

How can I access the property / value of an array that has been converted to an object? For example, I want to access a value at index 0,

$obj = (object) array('qualitypoint', 'technologies', 'India');
var_dump($obj->0);

error,

Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$' in C: ... convertting_to_object.php on line 11

+5
source share
2 answers

$obj->0 , PHP http://php.net/manual/en/language.variables.basics.php . ArrayObject, .

...

$array  = array('qualitypoint', 'technologies', 'India' , array("hello","world"));
$obj = (object) $array;
$obj2 = arrayObject($array);
function arrayObject($array)
{
    $object = new stdClass();
    foreach($array as $key => $value)
    {
        $key = (string) $key ;
        $object->$key = is_array($value) ? arrayObject($value) : $value ;
    }
    return $object ;
}
var_dump($obj2->{0}); // Sample Output
var_dump($obj,$obj2); // Full Output to see the difference 


$sumObject = $obj2->{3} ; /// Get Sub Object
var_dump($sumObject->{1});  // Output world

   string 'qualitypoint' (length=12)

object(stdClass)[1]
  string 'qualitypoint' (length=12)
  string 'technologies' (length=12)
  string 'India' (length=5)

    array
      0 => string 'hello' (length=5)
      1 => string 'world' (length=5)

object(stdClass)[2]
  public '0' => string 'qualitypoint' (length=12)
  public '1' => string 'technologies' (length=12)
  public '2' => string 'India' (length=5)
  public '3' => 
    object(stdClass)[3]
      public '0' => string 'hello' (length=5)
      public '1' => string 'world' (length=5)

:)

+2

:

$obj = (object) array('test' => 'qualitypoint', 'technologies', 'India');

var_dump($obj->test);

:

string(12) "qualitypoint"

$obj->0, : Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$'

, , :

foreach($obj as $x) {
    var_dump($x);
}

, , .

ArrayObject, :

$obj = new ArrayObject(array('qualitypoint', 'technologies', 'India'));

:

var_dump($obj[0]);

:

string(12) "qualitypoint"
+4

All Articles