PHP Passing an array as a reference

I am writing a class to sanitize strings passed to PHP via an ajax call, when I pass a string to this class it works fine, but it passes the array as a reference and it will not 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 impossible to insert links in PHP?

+3


source to share


2 answers


You loose the link inside the foreach. Change it to this and it will work:



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

      

+4


source


Your code doesn't change $array

, it changes $value

.



There are several ways to get around this, one foreach ($array as &$value)

, the other $array[$key]

in a loop.

+4


source







All Articles