stripslashes in Multi-Dimensional array [duplicate] - php

I need to stripslashes all items of an array at once.
Any idea how can I do this?

foreach ($your_array as $key=>$value) {
$your_array[$key] = stripslashes($value);
}
or for many levels array use this :
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
print_r($array);

For uni-dimensional arrays, array_map will do:
$a = array_map('stripslashes', $a);
For multi-dimensional arrays you can do something like:
$a = json_decode(stripslashes(json_encode($a)), true);
This last one can be used to fix magic_quotes, see this comment.

You can use array_map:
$output = array_map('stripslashes', $array);

I found this class / function
<?php
/**
* Remove slashes from strings, arrays and objects
*
* #param mixed input data
* #return mixed cleaned input data
*/
function stripslashesFull($input)
{
if (is_array($input)) {
$input = array_map('stripslashesFull', $input);
} elseif (is_object($input)) {
$vars = get_object_vars($input);
foreach ($vars as $k=>$v) {
$input->{$k} = stripslashesFull($v);
}
} else {
$input = stripslashes($input);
}
return $input;
}
?>
on this blog and it really helped me, and now i could pass variables, arrays and objects all through the same function...

Parse array recursevely, with this solution you don't have to dublicate your array
function addslashes_extended(&$arr_r){
if(is_array($arr_r))
{
foreach ($arr_r as &$val){
is_array($val) ? addslashes_extended($val):$val=addslashes($val);
}
unset($val);
}
else
$arr_r=addslashes($arr_r);
return $arr_r;
}

Any recursive function for array :
$result= Recursiver_of_Array($array, 'stripslashes');
code:
function Recursiver_of_Array($array,$function_name=false){
//on first run, we define the desired function name to be executed on values
if ($function_name) { $GLOBALS['current_func_name']= $function_name; } else {$function_name=$GLOBALS['current_func_name'];}
//now, if it's array, then recurse, otherwise execute function
return is_array($array) ? array_map('Recursiver_of_Array', $array) : $function_name($array);
}

Related

How do I remove surrounding spaces from each value in multidimensional array recursively

Each string value within my $arr array contains 2 preceeding white spaces. I would like to remove these spaces using the trim() method. Furthermore, I would like to do the same for any arrays within the $arr array assuming an infinite number of arrays within arrays. I attempted to do this recursively with no success.
Although there might be a built in php method to do this for me, I am learning, and would like to know why this code block doesn't work as well as what altercation can be made to fix it.
$arr = array(" one", " two", array(" three"));
function trimAll(&$array) {
foreach($array as $key => $value) {
if(gettype($value) !== "array") {
$array[$key] = trim($value);
} else {
trimAll($value);
}
}
}
trimAll($arr);
echo $arr[0];//"one" (worked)
echo $arr[1];//"two" (worked)
echo $arr[2][0];// " three"(didn't work)
The best/simplest function to call in this case is: array_walk_recursive(). There is no need to reinvent a function that php has already designed for just this purpose. It only visits "leaf nodes" so you don't need to check if it is processing an array-type element.
You merely need to modify the elements by reference (using & in the anonymous function parameter). I'll demo ltrim() since your input strings only have leading spaces, but you can use trim() to handle spaces on both sides of the string.
Code: (Demo) (PHP7.4 and higher version)
array_walk_recursive(
$arr,
function(&$v) {
$v = ltrim($v);
}
);
Output:
array (
0 => 'one',
1 => 'two',
2 =>
array (
0 => 'three',
),
)
As for your custom function, it could be written like this to provide a successful result:
function trimAll(&$array) { // modify the original input array by reference
foreach ($array as &$value) { // modify each value by reference
if (!is_array($value)) { // if it is not an array
$value = trim($value); // trim the string
} else {
trimAll($value); // recurse
}
}
}
trimAll($arr); // modify the array (no return value from function call)
var_export($arr); // print the array
You see, the reason your subarray element is not being affected is because there is no assignment occuring between $value and trimAll($value). The way you have set up trimAll, it does not return a value. So, even if you used:
} else {
$array[$key] = trimAll($value);
}
You would find that $array[$key] would be replaced by NULL. The solution is to make $value modifiable by reference by using &$value in the foreach loop.
And as if this answer wasn't long enough already, here is a way to reconfigure your function so that it returns the modified array instead of modifying the input array with no return.
function trimAll($array){ // input array is not modifiable
foreach ($array as &$value) { // $value IS modifiable
if (is_array($value)) { // if an array...
$value = trimAll($value); // assign recursion result to $value
} else { // not an array...
$value = trim($value); // trim the string
}
}
return $array; // return the new trimmed array
}
var_export(trimAll($arr)); // now trimAll() can be directly printed to screen
or if you wish to avoid modifying by reference entirely:
function trimAll($array) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$array[$key] = trimAll($value);
} else {
$array[$key] = trim($value);
}
}
return $array;
}
var_export(trimAll($arr));
Yes, there is a built-in PHP function which solves your problem. It is array_map()
But in your situation, you might need to do something like this:
Solution 1:
$input = array(" one", " two", array(" three"));
function removeSpaces($object)
{
if (is_array($object)) {
$object = array_map('trim', $object);
} else {
$object = trim($object);
}
return $object;
}
$output = array_map('removeSpaces', $input);
Solution 2:
$input = array(" one", " two", array(" three"));
function array_map_recursive(callable $func, array $array) {
return filter_var($array, \FILTER_CALLBACK, ['options' => $func]);
}
$output = array_map_recursive('trim', $input);
Cheers.
Simple method,
$arr = array(" one", " two", array(" three"));
function trimAll(&$array) {
foreach($array as $key => $value) {
if(gettype($value) !== "array") {
$array[$key] = trim($value);
} else {
$array[$key] = trimAll($value);
}
}
return $array;
}
trimAll($arr);

PHP Function Array values not changing

Ive created a function that takes an array as a parameter and changes all values to 4, but it doesn't work and i don't understand why. Really bothering me, could use help thank you!
$cup3 = array (1,4,3,5,7,2);
roll($cup3);
print_r($cup3);
function roll($array)
{
foreach($array as &$value)
{
$value = 4;
}
return $array;
}
Output: (1,4,3,5,7,2) instead of all 4s
Either pass by reference &$array to edit $cup3 directly:
roll($cup3);
print_r($cup3);
function roll(&$array)
{
foreach($array as &$value)
{
$value = 4;
}
}
Or use the return from the function:
$cup3 = roll($cup3);
print_r($cup3);
function roll($array)
{
foreach($array as &$value)
{
$value = 4;
}
return $array;
}

how can I get my php array data to persist?

When I query the data within the foreach loop it works, but makes a duplicate for each pass in the loop. I try to var_dump it anywhere else outside the loop and the data isn't there. Why won't my data persist outside the forEach loop?
<?php
$old_array = [10-2, 13=>"3452", 4=>"Green",
5=>"Green", 6=>"Blue", "green"=>"green",
"two"=>"green" ,"2"=>"green" , "rulebreak" =>"GrEeN",
"ninja"=>" Green ", ["blue" => "green", "green"=>"green", 2 => "itsGreen"] ];
$newArray = array();
function filter_Green($array) {
$find = "green";
$replace = "not green";
/* Same result as using str_replace on an array, but does so recursively for multi-dimensional arrays */
/* found here:
if (!is_array($array)) {
/* Used ireplace so that searches can be case insensitive */
return str_ireplace($find, $replace, $array);
}
foreach ($array as $key => $value) {
$newArray[$key] = $value;
if ($key == "green") {
$newArray[$key] = "not green";
}
if ($value == "green") {
$newArray[$value] = "not green";
}
}
return $newArray;
}
filter_Green($old_array);
var_dump($newArray);
?>
Expectation: When I run the function it should replace all instances of "green" with "not green" and save those into a $newArray. I have it returning $newArray but even then it doesn't seem to match up that the values are being saved into the newArray, hence why I'm doing var_dump to check if it's even working (it appears to not be)
Results: as it is setup, I get an empty array returned to me...It seems to work somewhat if I move var_dump($newArray) to within the foreach loop but that then duplicates the data for each pass.
if you want var_dump $newArray out side the function then you should declare $newArray as global in your function
<?php
$old_array = [10-2, 13=>"3452", 4=>"Green", 5=>"Green", 6=>"Blue", "green"=>"green", "two"=>"green" ,"2"=>"green" , "rulebreak" =>"GrEeN", "ninja"=>" Green ", ["blue" => "green", "green"=>"green", 2 => "itsGreen"] ];
$newArray = array();
function filter_Green($array) {
global $newArray;
$find = "green";
$replace = "not green";
/* Same result as using str_replace on an array, but does so recursively for multi-dimensional arrays */
if (!is_array($array)) {
/* Used ireplace so that searches can be case insensitive */
return str_ireplace($find, $replace, $array);
}
foreach ($array as $key => $value) {
$newArray[$key] = $value;
if ($key == "green") {
$newArray[$key] = "not green";
}
if ($value == "green") {
$newArray[$value] = "not green";
}
}
return $newArray;
}
filter_Green($old_array);
var_dump($newArray);
?>
But instead of declaring global in function, use returned value by filter_Green($old_array); as below
$result = filter_Green($old_array);
var_dump($result);

Using a delimited string, how do I get an array item relative to the parsed string?

Given a string in the format of "one/two" or "one/two/three", with / as delimiters, I need to get the value (as a reference) in a 2d array. In this specific case, I'm accessing the $_SESSION variable.
In the SessionAccessor::getData($str) function, I don't know what to put in there to make it parse the delimited string and return the array item. The idea is I won't know which array key I'm accessing. The function will be generic.
class SessionAccessor {
static &function getData($str) {
// $str = 'one/two/three'
return $_SESSION['one']['two']['three'];
}
}
/** Below is an example of how it will be expected to work **/
/**********************************************************/
// Get a reference to the array
$value =& SessionAccessor::getData('one/two/three');
// Set the value of $_SESSION['one']['two']['three'] to NULL
$value = NULL;
Here's the solution provided by #RocketHazmat here at StackOverflow:
class SessionAccessor {
static function &getVar($str) {
$arr =& $_SESSION;
foreach(explode('/',$str) as $path){
$arr =& $arr[$path];
}
return $arr;
}
}
From what you've described, it sounds like this is what you're after;
&function getData($str) {
$path = explode('/', $str);
$value = $_SESSION;
foreach ($path as $key) {
if (!isset($value[$key])) {
return null;
}
$value = $value[$key];
}
return $value;
}
EDIT
To also allow for the values to be set, it would be best to use a setData method. This should hopefully do what you hoped for;
class SessionAccessor {
static function getData($str) {
$path = explode('/', $str);
$value = $_SESSION;
foreach ($path as $key) {
if (!isset($value[$key])) {
return null;
}
$value = $value[$key];
}
return $value;
}
static function setData($str, $newValue) {
$path = explode('/', $str);
$last = array_pop($path);
$value = &$_SESSION;
foreach ($path as $key) {
if (!isset($value[$key])) {
$value[$key] = array();
}
$value = &$value[$key];
}
$value[$last] = $newValue;
}
}

PHP need to trim all the $_POST variables

Need you help in an unusal situation. I need to trim all the $_POST variables.
Is there any way I can do it at a single shot i.e., using a single function?
I know trim($_POST) won't do, I have to make some function like
function sanatize_post(){
foreach ($_POST as $key => $val)
$_POST[$key] = trim($val);
}
But, if you have any other suggestion or comment, please help me.
Thanks
Simply
$_POST = array_map("trim", $_POST);
But if $_POST members (even if 1 of them) is again an array itself, then use recursive version:
function array_map_deep( $value, $callback )
{
if ( is_array( $value ) ) {
foreach ( $value as $index => $item ) {
$value[ $index ] = array_map_deep( $item, $callback );
}
} elseif ( is_object( $value ) ) {
$object_vars = get_object_vars( $value );
foreach ( $object_vars as $property_name => $property_value ) {
$value->$property_name = array_map_deep( $property_value, $callback );
}
} else {
$value = call_user_func( $callback, $value );
}
return $value;
}
Here's a one-liner that will also work either on single values or recursively on arrays:
$_POST = filter_var($_POST, \FILTER_CALLBACK, ['options' => 'trim']);
use array_walk with a custom function
$clean_values = array();
array_walk($_POST, 'sanitize_post');
function sanitize_post($item, $key)
{
$clean_values[$key] = trim($item);
//optional further cleaning ex) htmlentities
}
array_walk($_POST, 'trim') (note that this and the idea might be broken as input name=foo[bar] is translated into an array)
Edit: the above is not correct. Try $_POST = array_map('trim', $_POST);.
You can also use this code I wrote in case you want to sanitize a string OR an array with one function:
function sanitize ($value) {
// sanitize array or string values
if (is_array($value)) {
array_walk_recursive($value, 'sanitize_value');
}
else {
sanitize_value($value);
}
return $value;
}
function sanitize_value (&$value) {
$value = trim(htmlspecialchars($value));
}
Simply use it like this:
$post_sanitized = sanitize($_POST);
$apple_sanitized = sanitize('apple');
Simply use this:
array_walk($_POST, create_function('&$val', '$val = trim($val);'));
and your $_POST is now trimmed.
The other answers did not work well with associative arrays. This recursive functions will trim all values inside a $_POST array all levels down.
// Trim all values of associative array
function trim_associative_array(&$input_array) {
if (is_array($input_array)) {
foreach ($input_array as $key => &$val) {
if (is_array($val)) {
trim_associative_array($val);
} else {
$input_array[$key] = trim($val);
}
}
}
}
I think it's better to use anonymous functions :
array_walk($_POST, function(& $value){
$value = trim($value);
});

Categories