Array apply function php

PHP Executing Upon an Array Applying a function to each element of an array

To apply a function to every item in an array, use array_map() . This will return a new array.

$array = array(1,2,3,4,5); //each array item is iterated over and gets stored in the function parameter. $newArray = array_map(function($item) < return $item + 1; >, $array); 

$newArray now is array(2,3,4,5,6); .

Instead of using an anonymous function, you could use a named function. The above could be written like:

function addOne($item) < return $item + 1; >$array = array(1, 2, 3, 4, 5); $newArray = array_map('addOne', $array); 

If the named function is a class method the call of the function has to include a reference to a class object the method belongs to:

class Example < public function addOne($item) < return $item + 1; >public function doCalculation() < $array = array(1, 2, 3, 4, 5); $newArray = array_map(array($this, 'addOne'), $array); >> 

Another way to apply a function to every item in an array is array_walk() and array_walk_recursive() . The callback passed into these functions take both the key/index and value of each array item. These functions will not return a new array, instead a boolean for success. For example, to print every element in a simple array:

$array = array(1, 2, 3, 4, 5); array_walk($array, function($value, $key) < echo $value . ' '; >); // prints "1 2 3 4 5" 

The value parameter of the callback may be passed by reference, allowing you to change the value directly in the original array:

$array = array(1, 2, 3, 4, 5); array_walk($array, function(&$value, $key) < $value++; >); 

For nested arrays, array_walk_recursive() will go deeper into each sub-array:

$array = array(1, array(2, 3, array(4, 5), 6); array_walk_recursive($array, function($value, $key) < echo $value . ' '; >); // prints "1 2 3 4 5 6" 

Note: array_walk and array_walk_recursive let you change the value of array items, but not the keys. Passing the keys by reference into the callback is valid but has no effect.

Читайте также:  Convert string to resource php

pdf

PDF — Download PHP for free

Источник

Easy way to apply a function to an array

What is the best way to map values of an array to a function? Is there any other ways to do this? TL;DR Have array with bytes like above, need to use on array keys and id’s to get readable id’s.

Easy way to apply a function to an array

I am aware of array_walk() and array_map() . However when using the former like so (on an old project) it failed

array_walk($_POST, 'mysql_real_escape_string'); 

Warning: mysql_real_escape_string() expects parameter 2 to be resource, string given.

So I went with this slightly more ugly version

foreach($_POST as $key => $value)

So why didn’t the first way work? What is the best way to map values of an array to a function?

The callback function passed to array_walk is expected to accept two parameters, one for the value and one for the key:

Typically, funcname takes on two parameters. The array parameter’s value being the first, and the key/index second.

But mysql_real_escape_string expects the second parameter to be a resource. That’s why you’re getting that error.

Use array_map instead, it only takes the value of each item and passes it to the given callback function:

array_map('mysql_real_escape_string', $_POST); 

The second parameter will be omitted and so the last opened connection is used.

If you need to pass the second parameter, you need to wrap the function call in another function, e.g. an anonymous function:

array_map(function($string) use ($link) < return mysql_real_escape_string($string, $link); >, $_POST); 

I know the OP asked to call a function, however in the cases where you do not really need to call a function you can define an anonymous one:

$ids = [1,2,3]; array_walk($ids,function(&$id)); 

It’s because the mysql_real_escape_string is being given two parameters, both string.

array_map() returns an array containing all the elements of arr1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()

mysql_real_escape_string() won’t work unless you’ve made a mysql connection first. The reason it is so cool is that it will escape characters in a way to fit the table type. The second [optional] argument is a reference to the mysql connection.

$_POST is always set up as key->value . So, you array_walk calls mysql_real_escape_string(value, key) . Notice the second argument is not a reference.

That is why it does not work. There are several solution already mentioned above.

JavaScript Function apply() Method, The apply() method is very handy if you want to use an array instead of an argument list. The apply() Method with Arguments The apply() method accepts …

Applying a function for each value of an array

Considering an array of strings:

$array = ('hello', 'hello1', 'hello2'); 

I need to preg_quote($value,’/’); each of the values.

I want to avoid using foreach . Array walk doesn’t work because it passes the key too.

array_walk($array,'preg_quote','/'); //> Errors, third parameter given to preg_quote 

Try array_map() [doc] with an anonymous function (>= 5.3):

$array = array_map(function($value)< return preg_quote($value, '/'); >, $array); 

Working demo

$newarray = array_map(function($a) , $input_array); 
array_map(function($elem) < return preg_quote($elem, '/'); >, $array); 

Use foreach . It’s made for that reason. But if you insist:

array_walk($arr, create_function('&$val', '$val = preg_quote($val, "/");')); 

PHP Arrays, In PHP, the array () function is used to create an array: array (); In PHP, there are three types of arrays: Indexed arrays — Arrays with a numeric index Associative …

Apply function to every array key

I am using Cassandra and I have saved some byte representations as ID. Everything is working fine, however that data (id) is no good for output.

$users = $db->get('1'); echo '
'; print_r($users); die(); 
Array ( [��� X��W��c_ ] => Array ( [id] => ��� X��W��c_ [name] => steve [surname] => moss ) [�*B�X��y�~p��~] => Array ( [id] => �*B�X��y�~p��~ [name] => john [surname] => doe ) ) 

As you can see ID's are some wierd characters, it's because they are byte representations in database. They actually look like \xf5*B\xa0X\x00\x11\xe1\x99y\xbf~p\xbc\xd1~ .

In PHPCASSA there is function CassandraUtil::import(); to which I can pass these bytes and it will return guid. It works fine, but I want my array to automatically converted from bytes to guids.

Only option I find is looping through every item in array and assigning new value to it. Somehow I think that it is not the best approach. Is there any other ways to do this?

TL;DR Have array with bytes like above, need to use CassandraUtil::import(); on array keys and id's to get readable id's. What is the most effective way of doing so.

Sorry, only saw the top level array key, I think you would have to run the function below as well as another one after:

function cassImportWalkRecur(&$item, $key) < if ($key == 'id') $item = CassandraUtil::import(); >$array = array_walk_recursive($array, 'cassImportWalkRecur'); 

That should apply it to the ID fields. If you need to check the data first, there maybe a way to detect the encoding, but I am not sure how to do that.

You should be able to create a function and use array_walk to traverse the array and update the keys. Something like:

function cassImportWalk($item, &$key) < $key = CassandraUtil::import(); >$array = array_walk($array, 'cassImportWalk'); 

Untested (also you may have to change the CassandraUtil usage), but should work.

Unless I am misunderstanding the question this can be done simply and cleanly like so:

$users = $db->get('1'); $keys = array_keys($users); $readableKeys = array_map("CassandraUtil::import",$keys); foreach($users as $currentKey => $subArray)

Would array_flip() all keys and values, then array_walk() and apply my function, before doing a final array_flip() .

Php - Applying a function for each value of an array, You can do (with PHP 5.3): array_map(function($elem) < return preg_quote($elem, '/'); >, $array); In PHP

Apply multiple functions to $_POST array in php

i was wondering, instead of tedious and repetitive code to sanitize input data is there a simpler way to manipulate the $_POST array and apply e.g. strip_tags() and remove_trailing_spaces() to all elements, in a successive loop?

function getSanitizedData($index) < return sanitize($_POST[$index]); >function sanitize($value)

Now instead of using $_POST, always use getSanitizedData function

Just use PHP Magic Quotes

How to use array_pop() and array_push() methods in PHP, The array_push () and array_pop () methods in PHP is used to perform insertions as well as deletions from the object. The article below illustrates the …

Источник

Оцените статью