Submit Tips/Quickies

Application Architecture : Miscellaneous

Associative Array to String and String to Associative Array functions

Submitted By: Stephen Calia
Date: 01/31/05 15:42

I like writng in PHP, but miss the easy perl way of changing an associative array to a list and then a list to a string. This makes it handy to pass a hidden value of an array as a string and then convert it back to an array when the next step of the script needs it. So, I wrote a couple of functions to do just that.

//array to string
function arraytostr ($array=array()) {

     $length = 0;
     $foreach ($array as $key => $value) {
          $keystring .= "$key ";
          $valuestring .= "$value ";
          $length++;
     }
		
     return array($length,$keystring,$valuestring);
}
//sting to array	
function strtoarray ($length="",$keystring="",$valuestring="") {
          $keys = explode(" ",$keystring);
          $values = explode(" ",$valuestring);
          for ($i=0; $i < $length; $i++) {
		$key = $keys[$i];
		$newarray[$key] = $values[$i];
          }
		
          return $newarray;
}


Comments:
Retriving Array info from mysqlsara07/27/05 00:41
 

If you are looking for help, please post on the appropriate forum here. Your questions will be answered much more quickly.

Add A Comment:

Name:

Email:

Subject:

Message:

To reduce spam posts, messages are now manually approved

You are not [logged in]. That means your account will not get credit for this post.