0

I have a question about the following code:

PHP function, takes in an array, recursively cycles through each level, does a string replace if single quote found and returns back array.

function escape_quote($data)
{
    $clean = array();

    foreach ($data as $key=>$val)
    {
        if (is_array($val))
        {
             $clean[$key] = escape_quote($val);
        } else {
             $val = str_replace("'", "''", $val);
             $clean[$key] = $val;
            }
    }

    return $clean;
}

Here is the array of data I am passing:

$vars = array
(
    'customer1' => array
    (
        'fname' => 'John',
        'lname' => "D'oe"
    ),
    'customer2' => array
    (
        'name'  => array
        (
            'fname' => 'John',
            'lname' => "D'oe"
        ),
        'address'   => '1234 street',
        'phone'     => '1234567899'

    )
);

I make this call to the function and pass the array to it:

$output = escape_quote($vars);
print_r($output);

My output on the screen:

Array ( [customer1] => Array ( [fname] => John [lname] => D''oe ) [customer2] => Array ( [name] => Array ( [fname] => John [lname] => D'oe ) [address] => 1234 street [phone] => 1234567899 ) )

My questions is why am I not getting the second "D'oe" returned as "D''oe"

if I echo out each value in the function rather than add to the clean array it will add the second "'" to both "D'oe". I am not sure what is missing... please help.

UPDATE:

I figured out the issue, made update to code. If the $val was an array I wasn't setting the $clean[$key] back equal to escape_quote($val).

2
  • "escape_quote($val);" - you don't assign the result to anything. Commented Mar 13, 2014 at 22:32
  • Please see my updates, I wasn't assigning the iteration equal to the clean array if $val was an array. Works now, thank you everyone! Commented Mar 13, 2014 at 22:46

1 Answer 1

2

This should work

function escape_quote($data)
{
    $clean = array();

    foreach ($data as $key=>$val)
    {
        $set = false;
        if (is_array($val))
        {
            $set = true;
            $val = escape_quote($val);
        }
        if(!$set){
            $val = str_replace("'", "''", $val);
        }
        $clean[$key] = $val;
    }

return $clean;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.