1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Assoc Array to String & String to Assoc Array

Discussion in 'PHP' started by pradeep, Oct 17, 2005.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    I like coding PHP, in Perl we can change an associative array to a list then to a string. In case if we wish to do the same in PHP, we need to write some user functions for that purpose.
    Here are two functions which will convert Array to String and vice-versa.

    PHP:
    //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;
     }
     
    Last edited by a moderator: Oct 17, 2005

Share This Page