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?
You lose the reference inside the foreach. Change it to this and it'll work:
foreach( $array as $key => &$value ) {
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With