Workaround for no array_map for keys and values - php

I'd like a function that fills an array from a callback supplying key and value, to looplessly refactor e.g. this:
foreach(array_slice($argv,1) as $arg)
if( preg_match('~^([^=]*)=([^=]*)$~',$arg,$matches)) $_SERVER[$matches[1]] = $matches[2];
What's the nearest available?

$_SERVER += array_reduce(array_slice($argv, 1), function (array $args, $arg) {
return $args + preg_match('~^([^=]*)=([^=]*)$~', $arg, $m) ? [$m[1] => $m[2]] : [];
}, []);
Whether this is really anymore sensible than a straight foreach loop is very debatable, but hey...

Probably the easiest way to do this would be to use array_walk to walk the array and apply the results to the superglobal.
array_walk(array_slice($argv,1), function ($val) {
list($key, $value) = explode("=", $val, 2);
if (isset($value){
$_SERVER[$key] = $value;
}
});
If you had wanted to do something like this targeting a non super global you would just need to add use (&$array) after the function keyword in the callback.

Related

array_walk_recursive can't work when I use function htmlspecialchars?

I use array_walk_recursive to apply htmlspecialchars on my array value, but it didn't work, htmlspecialchars works when I use it manully;
Here is my code:
$new[] = "<a href='test'>Test</a><li><div>";
var_dump(array_walk_recursive($new,'htmlspecialchars')); // true
var_dump($new) ; // no change
That is because the original array is not modified unless you modify it yourself in the callback function.
Your callback function is basically:
function($item, $key) {
htmlspecialchars($item);
}
So while the function is called, nothing is stored and the original array is not changed.
If you want to modify the value in the function, you can pass it by reference:
function(&$item, $key) {
$item = htmlspecialchars($item);
}
So the result would look like:
$new[] = "<a href='test'>Test</a><li><div>";
array_walk_recursive($new, function(&$item, $key) {
$item = htmlspecialchars($item);
});
var_dump($new) ; // change!
You can of course define a separate function if you would prefer that.
In the definition of array_walk_recursive:
array_walk_recursive — Apply a user function recursively to every
member of an array
So you need to create a user defined function that uses htmlspecialchars like this:
$new[] = "<a href='test'>Test</a><li><div>";
array_walk_recursive($new, "specialChars");
var_dump($new);
function specialChars(&$value) {
$value = htmlspecialchars($value);
}
And this will print:
array (size=1)
0 => string '<a href='test'>Test</a><li><div>' (length=56)

Find an Object in an array by comparing Object->value to all Object->values in array PHP

So my array contains objects like this:
$arr = array(
new Card('10', 'Spades'),
new Card('Jack', 'Diamonds'),
new Card('King', 'Spades')
);
Now I have a function:
function hasCard(Card $card) {
if (in_array($card, $arr)) return true;
return false;
}
Now above does not really work since I need to compare ($card->rank == $arr[$x]->rank) for each element in that $arr without looping. Is there a function on PHP that allows you to modify the compareTo method of array_search?
I'd suggest using array_filter here. (Note: make sure $arr is available inside the hasCard function)
function hasCard(Card $card) {
$inArray = array_filter($arr, function($x) use($card){
return $x->rank === $card->rank;
});
return count($inArray) > 0;
}
DEMO: https://eval.in/166460
The $arr variable is not going to be available within the function hasCard, unless you pass it as a parameter.
To answer your question, look at array_filter. This will get you a callable function in which you can pass the $arr and $card as parameters.

Passing location in subarray as string

I have a function that searches a multidimensional array for a key, and returns the path
inside the array to my desired key as a string.
Is there any way I can use this string in php to reach this place in my original array, not to get to the value but to make changes to this specific bracnch of the array?
An example:
$array = array('first_level'=>array(
'second_level'=>array(
'desired_key'=>'value')));
in this example the function will return the string:
'first_level=>second_level=>desired_key'
Is there a way to use this output, or format it differently in order to use it in the following or a similar way?
$res = find_deep_key($array,'needle');
$array[$res]['newkey'] = 'injected value';
Thanks
If the keys path is safe (e.g. not given by the user), you can use eval and do something like:
$k = 'first_level=>second_level=>desired_key';
$k = explode('=>', $k);
$keys = '[\'' . implode('\'][\'', $k) . '\']';
eval('$key = &$array' . $keys . ';');
var_dump($key);
I think you want to do a recursive search in the array for your key? Correct me if i am wrong.
Try this
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
Taken from here http://in3.php.net/manual/en/function.array-search.php#91365
You need something like:
find_key_in_array($key, $array, function($foundValue){
// do stuff here with found value, e.g.
return $foundValue * 2;
});
and the implementation would be something like:
function find_key_in_array($key, $array, $callback){
// iterate over array fields recursively till you find desired field, then:
...
$array[$key] = $callback($array[$key]);
}
If you need to append some new sub-array into multidimensional complex array and you know where exactly it should be appended (you have path as a string), this might work (another approach without eval()):
function append_to_subarray_by_path($newkey, $newvalue, $path, $pathDelimiter, &$array) {
$destinationArray = &$array;
foreach (explode($pathDelimiter, $path) as $key) {
if (isset($destinationArray[$key])) {
$destinationArray = &$destinationArray[$key];
} else {
$destinationArray[$newkey] = $newvalue;
}
}
}
$res = find_deep_key($array,'needle');
append_to_subarray_by_path('newkey', 'injected value', $res, '=>', $array);
Of course, it will work only if all keys in path already exist. Otherwise it will append new sub-array into wrong place.
just write a function that takes the string and the array. The function will take the key for each array level and then returns the found object.
such as:
void object FindArray(Array[] array,String key)
{
if(key.Length == 0) return array;
var currentKey = key.Split('=>')[0];
return FindArray(array[currentKey], key.Remove(currentKey));
}

abs of an array

Which is the easy way of getting the abs of an array in php? It has to be a better way. This works, but in multidimensional array it has some limitations
function make_abs($numbers) {
$abs_array = array();
foreach($numbers as $key=>$value)
$abs_array[$key] = abs($value);
return $abs_array;
}
Use a map function:
array_map("abs", $numbers)
http://php.net/manual/en/function.array-map.php
Your variant using references (this does not solve your recursion problem, just FYI):
function make_abs(&$numbers)
{
foreach($numbers as &$value)
$value = abs($value)
;
}
For the recursion problem, you need to step into each array:
function make_abs(&$numbers)
{
foreach($numbers as &$value)
is_array($value) ? make_abs($value) : $value = abs($value)
;
}
PHP itself has a somewhat handy function for that, array_walk_recursiveDocs. The problem with that function is, it expects the callback to have two parameters, value (by reference) and key. Many PHP functions do not fit those requirements. You can work around that by creating yourself a helper function to use any function that only takes one parameter and returns the modified value. You pass the function as with array_mapDocs:
function array_walk_recursive_map(array &$array, $callback)
{
$byRef = function(&$item, $key) use ($callback)
{
$item = $callback($item);
};
array_walk_recursive($array, $byRef);
}
# Usage:
array_walk_recursive_map($numbers, 'abs');
Hope this is helpful.
You could do array_walk_recursive($numbers, 'make_abs');
http://php.net/manual/en/function.array-walk-recursive.php
Edit
$numbers = array(1, 35, 107);
function make_abs(&$item,$key) { // use with reference
$item = abs($item);
}
array_walk_recursive($numbers, 'make_abs');
This example works with multidimensional arrays.

php: array_replace_recursive alternative

I need a solution for array_replace_recursive, because my php-version isn't high enough. I want to use this code:
$_GET = array_replace_recursive($_GET, array("__amp__"=>"&"));
easy, isn't it?
On the PHP docs page for array_replace_recursive, someone posted the following source code to use in place of it:
<?php
if (!function_exists('array_replace_recursive'))
{
function array_replace_recursive($array, $array1)
{
function recurse($array, $array1)
{
foreach ($array1 as $key => $value)
{
// create new key in $array, if it is empty or not an array
if (!isset($array[$key]) || (isset($array[$key]) && !is_array($array[$key])))
{
$array[$key] = array();
}
// overwrite the value in the base array
if (is_array($value))
{
$value = recurse($array[$key], $value);
}
$array[$key] = $value;
}
return $array;
}
// handle the arguments, merge one by one
$args = func_get_args();
$array = $args[0];
if (!is_array($array))
{
return $array;
}
for ($i = 1; $i < count($args); $i++)
{
if (is_array($args[$i]))
{
$array = recurse($array, $args[$i]);
}
}
return $array;
}
}
?>
The code above by #Justin is ok, save for 2 things:
Function is not readily available at start of php execution be cause it is wrapped in if(). PHP docu says
When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called.
Most importantly; calling the function twice results in fatal error.
PHP docu says
All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.
So I just moved the recurse function outside array_replace_recursive function and it worked well. I also removed the if() condition and renamed it to array_replace_recursive_b4php53 for fear of future upgradings

Categories