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,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    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

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice