note 109953 modified in function.serialize by danbrown

From: Date: Thu, 06 Sep 2012 16:54:40 +0000
Subject: note 109953 modified in function.serialize by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-190544@lists.php.net to get a copy of this message
When you serialize an array the internal pointer will not be preserved. Apparently this is the expected behavior but was a bit of a gotcha moment for me. Copy and paste example below.&#13;&#10;&#13;&#10;&#60;?php&#13;&#10;//Internal Pointer will be 2 once variables have been assigned.&#13;&#10;$array = array();&#13;&#10;$array[] = 1;&#13;&#10;$array[] = 2;&#13;&#10;$array[] = 3;&#13;&#10;&#13;&#10;//Unset variables. Internal pointer will still be at 2. &#13;&#10;unset($array[0]);&#13;&#10;unset($array[1]);&#13;&#10;unset($array[2]);&#13;&#10;&#13;&#10;//Serialize&#13;&#10;$serializeArray = serialize($array);&#13;&#10;&#13;&#10;//Unserialize&#13;&#10;$array = unserialize($serializeArray);&#13;&#10;&#13;&#10;//Add a new element to the array&#13;&#10;//If the internal pointer was preserved, the new array key should be 3.&#13;&#10;//Instead the internal pointer has been reset, and the new array key is 0.&#13;&#10;$array[] = 4;&#13;&#10;&#13;&#10;//Expected Key - 3&#13;&#10;//Actual Key - 0&#13;&#10;echo &#34;&#60;pre&#62;&#34; , print_r($array, 1) , &#34;&#60;/pre&#62;&#34;;&#13;&#10;?&#62; --was-- When you serialize an array the internal pointer will not be preserved. Apparently this is the expected behavior but was a bit of a gotcha moment for me. Copy and paste example below. //Internal Pointer will be 2 once variables have been assigned. $array = array(); $array[] = 1; $array[] = 2; $array[] = 3; //Unset variables. Internal pointer will still be at 2. unset($array[0]); unset($array[1]); unset($array[2]); //Serialize $serializeArray = serialize($array); //Unserialize $array = unserialize($serializeArray); //Add a new element to the array //If the internal pointer was preserved, the new array key should be 3. //Instead the internal pointer has been reset, and the new array key is 0. $array[] = 4; //Expected Key - 3 //Actual Key - 0 echo "<pre>" , print_r($array, 1) , "</pre>"; http://php.net/manual/en/function.serialize.php

« previous php.notes (#190544) next »