sahmed sahmed - 5 months ago 8
PHP Question

When serializing array, won't serialize last number

In this program I'm trying to take a serialized array out of a MySQL table and then adding one result to it, and then re-serializing that array and putting it back into the table. Here is my code:

for($i = 0; $i < $count; $i++){
$query = "SELECT `assignment_assigned` FROM `users` WHERE isAdmin = 0 LIMIT 1";
$result = mysqli_query($con, $query);
if($result === FALSE) {
echo "Failed".mysql_error();
} else {
$unserializedVal = unserialize(implode(mysqli_fetch_array($result)));
$array = array_push($unserializedVal, $val);
$serializedVal = serialize($unserializedVal);
}
<h1><?php print_r($unserializedVal); ?></h1>


When I do this, I retrieve the array and can unserialize it just fine, but when I try to reserialize it, this shows up:

a:8:{i:0;i:2;i:1;i:3;i:2;i:4;i:3;i:5;i:4;i:6;i:5;i:7;i:6;i:8;i:7;s:2:"10";}


The original serialized string was this:

a:7:{i:0;i:2;i:1;i:3;i:2;i:4;i:3;i:5;i:4;i:6;i:5;i:7;i:6;i:8;}


The array before I append the last numeral looks like this:

Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 [5] => 7 [6] => 8 )


And after appending the last number:

Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 [5] => 7 [6] => 8 [7] => 10 )


Any help here?

Answer

You're getting s:2:"10"; added to your serialized array because the value you added is a string, not an integer.

You could convert the string to an integer using intval().

$val = intval($val);

For error checking intval() will return 0.

$unserializedVal = unserialize(mysqli_fetch_array($result));
$val = intval($val);
// add error handling here
$array = array_push($unserializedVal, $val);
$serializedVal = serialize($unserializedVal);

Note: removed implode() as pointed out by others.

Comments