PHP Associative array from get_object_vars does not work for integer keys
Get the solution ↓↓↓I have an object used for storing current quantities of a product at various sites. The Site ID is used to indicate where the stock is, and it is used as an object key to point to the quantity.
The product can have stock at site 0 and site 2, but not necessarily have anything at site 1, thus it does not have to be set.
I tried using PHP get_object_vars() function and got the associative array, but when trying to access the values using the array_keys() function, they did not yield any output. Running a test script below, I found that using integers for the objects did not work as expected.
<?php
$obj = new stdClass();
$a = 'a';
$b = 1;
$obj->$a = 3;
$obj->$b = 6;
$vars = get_object_vars($obj);
$keys = array_keys($vars);
var_dump($vars);
echo("<br>");
var_dump($keys);
echo("<br><br>");
var_dump($vars[$keys[0]]);
echo("<br>");
var_dump($vars[$keys[1]]);
echo("<br><br>");
$vars = array("a"=>3,1=>6);
$vars['1'] = 6;
$keys = array_keys($vars);
var_dump($vars);
echo("<br>");
var_dump($keys);
echo("<br><br>");
var_dump($vars[$keys[0]]);
echo("<br>");
var_dump($vars[$keys[1]]);
?>
The output I got was:
array(2) { ["a"]=> int(3) ["1"]=> int(6) }
array(2) { [0]=> string(1) "a" [1]=> string(1) "1" }
int(3)
NULL
array(2) { ["a"]=> int(3) [1]=> int(6) }
array(2) { [0]=> string(1) "a" [1]=> int(1) }
int(3)
int(6)
Is it possible to access the object properties if they were saved as integers?
Answer
Solution:
It seems that the PHP version that I ran my test scripts on was a bit outdated, tried my code on an up-to-date version and didn't returnNULL
. I guss this wasn't a bug or problem.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: please make sure the php redis extension is installed and enabled.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.