简体   繁体   中英

PHP Passing array as reference

I am writing a class to sanitize strings passed to PHP through an ajax call, when I pass a string into this class it works fine but passing the array as a reference and it won't work.

class Sanitize {

    public static function clean (&$str) {
        self::start($str);
    }

    public static function cleanArray (&$array) {
        if (self::arrayCheck($array)) {
            foreach ($array as $key => $value) {
                if (self::arrayCheck($value)) {
                    self::cleanArray($value);
                } else {
                    self::clean($value);
                }
            }
        } else {
            throw new Exception ('An array was not provided. Please try using clean() instead of cleanArray()');
        }
    }

    private static function start (&$str) {
        $str .= '_cleaned';
    }

    private static function arrayCheck ($array) {
        return (is_array($array) && !empty($array));
    }
}

Test Code:

$array = array(
    'one' => 'one',
    'two' => 'two',
    'three' => 'three',
    'four' => 'four'
);
echo print_r($array, true) . PHP_EOL;
Sanitize::cleanArray($array);
echo print_r($array, true) . PHP_EOL;

Output:

Array
(
    [one] => one
    [two] => two
    [three] => three
    [four] => four
)

Array
(
    [one] => one
    [two] => two
    [three] => three
    [four] => four
)

Is there something I am missing, or is it not possible to nest reference passes in PHP?

Your code does not modify the $array , it modifies $value .

There're couple of ways to get around that, one is foreach ($array as &$value) , the other is modify $array[$key] inside the loop.

You lose the reference inside the foreach. Change it to this and it'll work:

foreach( $array as $key => &$value ) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM