up vote 0 down vote favorite

Hi,

How can I make the code below into a function?

# split the string by string on boundaries formed by the string delimiter will split the value into an array like the example below,
# Array
# (
#     [0] => pg_cat_id=1
#     [1] => tmp_id=4
#     [2] => parent_id=2
# )
$array_parent = explode("&", $string);
//print_r($array_parent);

# now loop the array.
for($i = 0; $i < count($array_parent); $i++)
{   
    # split the array into smaller arrays with the string delimiter, like the example below,
    #   Array
    #   (
    #       [0] => pg_cat_id
    #       [1] => 1
    #   )
    #   Array
    #   (
    #       [0] => tmp_id
    #       [1] => 4
    #   )
    #   Array
    #   (
    #       [0] => parent_id
    #       [1] => 2
    #   )
    $array_child = explode("=", $array_parent[$i]);
    //print_r($array_child);

    # loop each of the array.
    for($a = 0; $a < count($array_child); $a++)
    {   
        # get the first value in each array and store it in a variable.
        $v = $array_child[0];

        # make the variable variable (sometimes it is convenient to be able to have variable variable names. 
        # that is, a variable name which can be set and used dynamically. a variable variable takes the value 
        # of a variable and treats that as the name of a variable). 
        ${$v} = $array_child[1];
    }
}

so that I can call the function whenever I need it, such as below,

$string = 'pg_cat_id=1&tmp_id=4&parent_id=2';

echo stringToVarVars($string);

echo $tmp_id; // I will get 4 as the restult.

Many thanks, Lau

link|flag

2  
Don't do that. Don't try to re-implement register_globals... – ircmaxell Aug 20 at 13:20

4 Answers

up vote 1 down vote accepted

Full working code here. No need to create a function. Just two line of codes are enough.

<?php
$string = 'pg_cat_id=1&tmp_id=4&parent_id=2';

parse_str($string, $result);
extract($result);

echo $tmp_id;  // output: 4
?>
link|flag
oh thank you so much. this save lots of my tedious code! thanks :) – lauthiamkok Aug 20 at 13:26
You're welcome. – shamittomar Aug 20 at 13:31
up vote 3 down vote

Are you parsing a query string? You could use parse_str().

link|flag
thanks so much. this is so greater than what I did! thanks :) – lauthiamkok Aug 20 at 13:27
up vote 1 down vote

Use the global keyword to set variables outside of the function.

function stringToVarVars($string)
{
    ...
    global ${$v};
    ${$v} = ...;
}
link|flag
thank you and thanks for this global!! :-))) – lauthiamkok Aug 20 at 13:32
up vote 0 down vote

Use an array instead of variable variables:

function stringToVarVars($string)
{
    ...
    $result[$v] = ...;
    return $result;
}

$variables = stringToVarVars($string);
echo $variables['tmp_id'];
link|flag
this works too! thank you :-) – lauthiamkok Aug 20 at 13:36

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.