How to use array_walk_recursive - php

How can I use array_walk_recursive() instead of this:
function check_value($val){
if(is_array($val)){
foreach($val as $key => $value)
$val[$key] = check_value($value);
return $val;
}
return clean_value($val);
}
?

I think this should do the same thing. Note that argument of a function is passed as a reference (i.e. &$value).
array_walk_recursive($array, function(&$value) {
$value = clean_value($value);
});
For older PHP versions:
function check_value(&$value) {
$value = clean_value($value);
}
array_walk_recursive($array, 'check_value');

I would rewrite the clean_value function to take a reference argument.
For example, these two snippets are functionally identical:
1:
function clean_value($value) {
//manipulate $value
return $value;
}
$value = clean_value($value);
and
2:
function clean_value(&$value) {
//manipulate $value
}
clean_value($value);
For the latter (2), we can use it in array_walk_recursive as follows:
array_walk_recursive($value_tree, 'clean_value');
If we can't edit clean_value, I would solve it as follows:
$clean_by_reference = function(&$val) {
$val = clean_value($val);
};
array_walk_recursive($value_tree, $clean_by_reference);
Hope this helps!

This should work:
function check_value ( $val ) {
if ( is_array ( $val ) ) array_walk_recursive ( $val, 'check_value' );
return clean_value ( $val );
}

Related

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;
}

stripslashes in Multi-Dimensional array [duplicate]

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);
}

Merge and sum two associatve arrays in PHP

Given these two arrays:
$first=array(
'books'=>1,
'videos'=>5,
'tapes'=>7,
);
$second=array(
'books'=>3,
'videos'=>2,
'radios'=>4,
'rc cars'=>3,
);
I would like to combine them so that I end up with
$third=array(
'books'=>4,
'videos'=>7,
'tapes'=>7,
'radios'=>4,
'rc cars'=>3,
);
I saw a function here: How to sum values of the array of the same key? but it looses the Key.
You can use something along the lines of:
function sum_associatve($arrays){
$sum = array();
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
if (isset($sum[$key])) {
$sum[$key] += $value;
} else {
$sum[$key] = $value;
}
}
}
return $sum;
}
$third=sum_associatve(array($first,$second));
Just to be different... Uses func_get_args(), closures and enforces arguments to be arrays:
function sum_associative()
{
$data = array();
array_walk($args = func_get_args(), function (array $arg) use (&$data) {
array_walk($arg, function ($value, $key) use (&$data) {
if (isset($data[$key])) {
$data[$key] += $value;
} else {
$data[$key] = $value;
}
});
});
return $data;
}

Make new array from specifed string?

I have this kind of simple array:
$puctures=array('1_noname.jpg','2_new.jpg','1_ok.jpg','3_lets.jpg','1_stack.jpg','1_predlog.jpg','3_loli.jpg');
I want to make new array that i will only have elements thats starts with 1_
Example
$new=array('1_noname.jpg','1_ok.jpg','1_stack.jpg','1_predlog.jpg');
Something like array_pop but how?
See array_filter():
$new = array_filter(
$puctures,
function($a) {return substr($a, 0, 2) == '1_'; }
);
A simple loop will do.
foreach ($pictures as $picture) {
if (substr($picture, 0, 2) == "1_") {
$new[] = $picture;
}
}
Use array_filter() to get your array:
$new = array_filter($puctures, function($item)
{
//here strpos() may be a better option:
return preg_match('/^1_/', $item);
});
This examples uses array_push() & strpos()
$FirstPictures = array();
foreach( $pictures as $pic => $value ) {
if ( strpos( $value, '1_' ) !== 0 ) {
array_push( $FirstPictures, $pic );
}
}
$puctures=array('1_noname.jpg','2_new.jpg','1_ok.jpg','3_lets.jpg','1_stack.jpg','1_predlog.jpg','3_loli.jpg');
$new=array();
foreach($puctures as $value)
{
if(strchr($value,'1'))
$new[]=$value;
}
echo "<pre>"; print_r($new);

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