Using WordPress ‘add_magic_quotes()’ PHP function

The add_magic_quotes() WordPress PHP function sanitizes an array by adding slashes to the array’s content.

Usage

To use the add_magic_quotes() function, pass an array as the argument. The function will walk through the array and sanitize its contents by adding slashes.

$input_array = array("Hello","World's","Best","Website");
$result_array = add_magic_quotes($input_array);

In this case, the output would be an array with each string having added slashes before any special characters.

Parameters

  • $input_array (array): This is the array that you want to sanitize. The function will walk through each element in the array and add slashes to sanitize the content.

More information

See WordPress Developer Resources: add_magic_quotes()
This function was implemented in WordPress 2.0.0.

Examples

Sanitizing a simple array

In this example, we have an array of strings that we want to sanitize using the add_magic_quotes() function.

$input_array = array("Hello","World's","Best","Website");
$result_array = add_magic_quotes($input_array);
print_r($result_array);

The output will be:
Array ( [0] => Hello [1] => World\'s [2] => Best [3] => Website )

Sanitizing an array with special characters

In this case, we have an array with strings that include special characters.

$input_array = array("It's","a","bea@utiful","day!");
$result_array = add_magic_quotes($input_array);
print_r($result_array);

The output will be:
Array ( [0] => It\'s [1] => a [2] => bea@utiful [3] => day! )

Sanitizing a multi-dimensional array

The add_magic_quotes() function can also sanitize multi-dimensional arrays.

$input_array = array(array("Hello","World's"), array("Best","Website"));
$result_array = add_magic_quotes($input_array);
print_r($result_array);

The output will be:
Array ( [0] => Array ( [0] => Hello [1] => World\'s ) [1] => Array ( [0] => Best [1] => Website ) )

Sanitizing an array of integers

The add_magic_quotes() function can also work with arrays of integers, though it won’t have any effect as there are no characters to escape in integers.

$input_array = array(1, 2, 3, 4, 5);
$result_array = add_magic_quotes($input_array);
print_r($result_array);

The output will be:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )

Sanitizing an empty array

The add_magic_quotes() function will return an empty array if an empty array is passed to it.

$input_array = array();
$result_array = add_magic_quotes($input_array);
print_r($result_array);

The output will be: Array ( )