Special Offer - Get $90 Discount and Host Your Dream Web Site @ Dreamhost for 1 Year Click Here. Promo Code SLJ345
Back To Top
WordPress Web Application Development
Develop Powerfull Web Applications Using Cutting Edge WordPress Development Techniques

How To Convert Key-Value Pairs To An Object Using PHP

on 2011/02/17 9:09 AM stored in: Uncategorized and tagged:

What are Key-Value pairs ?

Key-Value pairs are a common data handling method used in web development. Its easy to keep and manipulate the data in Key-value pairs when we do programming. When we pass the data to another page,function or external source we can associate the values we want to pass with a key.

Example: name=John&age=23

There are 2 key-value pairs seperated by ‘&’ sign. name=john and age=23 are the 2 pairs.

 

Why do we have to convert key-value pairs ?

Normally we get this key value pairs as a long string. To access a specific value we need to break this string in to key-value pairs.

 

How can we convert string into key-value pairs ?

  • First we have to break the string using the key-value pair separator
  • In the previous example ‘&’ is the key-value pair separator
  • Next we have to break the string using the key-value separator
  • In the previous example ‘=’ is the key-value separator
  • Then we can assign the key and value to stranded class object and use in development.

 

Source Code

function convertStringToKeyValuePairs($stringToConvert, $pairSeperator, $keyValueSeperator) {
    $pairs = explode($pairSeperator, $stringToConvert);

    $obj = new StdClass();

    foreach ($pairs as $num => $pair) {

        $break_pair = explode($keyValueSeperator, $pair);
        $obj->$break_pair[0] = $break_pair[1];

    }

    return $obj;
}

 

Code Explanation

  • First we have to parse the string , pair separator and key-value separator to convertStringToKeyValuePairs() function
  • explode inside the function will break the string to an array of key-value pairs
  • Then we have to traverse through each key-value pair using a loop (for,foreach or while)
  • Inside the loop , key-value pair will be broken into a array ($break_pair) using key-value separator.
  • Next we assign the key ($break_pair[0]) as a variable of php standard class object and value ($break_pair[1] ) as the value of the variable.
  • Then we can access the values using $obj->$key.

 

How To Use


include_once 'key_value_converter.php'
$str = "name=hiller&age=34";
$obj = convertStringToKeyValuePairs($str, "&", "=");

echo $obj->name;
echo $obj->age;

 

Examples for Key-Value Pairs

  • Passing the values in url string and accessing with $_GET.
  • Accessing the values in an associative array.
  • Using the values returned from Paypal instant payment notification

 

Download Source Code

Leave a Reply

Follow Us On Facebook