3

Array cannot get value by key from unserialize. It show error Undefined offset, but the array has the index call "1134". How can I get the index 1134 value?

$original = unserialize('O:8:"stdClass":1:{s:4:"1134";i:1;}');

$result = (array)$original;
print_r ($result); //Array ( [1134] => 1 ) 

print_r($result["1134"]); //Undefined offset: 1134
print_r($result['1134']); //Undefined offset: 1134
print_r($result[1134]); //Undefined offset: 1134
3
  • Sorry - I can't reproduce this problem - they all just print 1. (in version 7.2) Commented Oct 26, 2018 at 7:10
  • check in version 5 @NigelRen :-3v4l.org/h0eWQ Commented Oct 26, 2018 at 7:11
  • @AlivetoDie thanks, always a problem with variations in different versions. Commented Oct 26, 2018 at 7:13

4 Answers 4

2

You've to iterate over your unserialized data and then store it into an array:

<?php
$original = unserialize('O:8:"stdClass":1:{s:4:"1134";i:1;}');
$arr = [];
foreach($original as $key => $values) {
    $arr[$key] = $values;
}
echo $arr[1134] // outputs 1
?>

Output:-https://3v4l.org/B94OS#v5638

Sign up to request clarification or add additional context in comments.

Comments

2

Try this, you can use it like object or may like to use get_object_vars() to use it like array or may use type casting.

<?php
$original = unserialize('O:8:"stdClass":1:{s:4:"1134";i:1;}');
var_dump($original->{1134}); //Object
var_dump(get_object_vars($original)['1134']); //array
?>

1 Comment

@D.Dimitrov updated my answer to make it better, that may make things more clear for you.
2

Your code is running fine in my PHP version 7.2. It seems you are using PHP 5.4 or 5.6. Anyway I have updated code for your php version and hope it will work.

 $original = unserialize('O:8:"stdClass":1:{s:4:"1134";i:1;}');
 $result = json_decode(json_encode($original), True);
 print_r ($result);
 print_r($result["1134"]); 
 print_r($result['1134']); 
 print_r($result[1134]);

Comments

1
$original = unserialize('O:8:"stdClass":1:{s:4:"1134";i:1;}');

$result = (array)$original;
print_r($result[1134]); //print 1 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.