Question

I have following problem in PHP:

print_r() says it's the same, gettype() says same type, but the last output works not for both cases although they should be the same!

This looks very strange to me.

code and output:

$docdatau = get_object_vars(json_decode($docdata));
$docdatau2 = (array)json_decode($docdata);

echo "1\n";
echo gettype($docdatau);
echo "\n";
echo "--------------------------------------\n";
print_r($docdatau);
echo "--------------------------------------\n";

echo "2\n";
echo gettype($docdatau2);
echo "\n";
echo "--------------------------------------\n";
print_r($docdatau2);

echo "out1\n";
echo "--------------------------------------\n";
print_r($docdatau[0]);
echo "out2\n";
echo "--------------------------------------\n";
print_r($docdatau2[0]);

The output:

1
array
--------------------------------------
Array
(

    [0] => stdClass Object
        (
            [produkt] => Produkt 2
            [laufzeit] => 24
            [addtext] => sdsd
            [provision] => 39
        )

    [1] => stdClass Object
        (
            [produkt] => Produkt 1
            [laufzeit] => 
            [addtext] => 
            [provision] => 0
        )

)
--------------------------------------
2
array
--------------------------------------

Array
(

    [0] => stdClass Object
        (
            [produkt] => Produkt 2
            [laufzeit] => 24
            [addtext] => sdsd
            [provision] => 39
        )

    [1] => stdClass Object
        (
            [produkt] => Produkt 1
            [laufzeit] => 
            [addtext] => 
            [provision] => 0
        )

)
out1
--------------------------------------
stdClass Object
(
    [produkt] => Produkt 2
    [laufzeit] => 24
    [addtext] => sdsd
    [provision] => 39
)
out2
--------------------------------------
--------------------------------------

out1 and out2 should produce the same results but don't.

Perhaps anybody has a hint for me?

Was it helpful?

Solution

There are several PHP bugs about it:

The same things happens here:

$obj->{0} = "hello";
$arr = (array)$obj;
echo $arr[0];

It happens because the "0" is used as string array key, whereas $arr[0] searches for the integer array key. It is documented in the PHP documentation simply by stating: integer properties are unaccessible (link).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top