Multiple functions using array_map [duplicate] - php

This question already has answers here:
Array_Map using multiple native callbacks?
(3 answers)
Closed 1 year ago.
array_map accepts string as its first argument. Is there a way, to use arrays instead of strings, like:
.... array_map( array('trim','urlencode'), $my_array);
so I could attach multiple functions.

You can define a function to combine these trim and urlencode functions. Then use the new function name or the new function as the first parameter of the array_map() function.
array_map(function($v){
$v = trim($v);
$v = urlencode($v);
return $v
}, $array);

You can do it this way also. Reference: create_function()
Warning: This function has been DEPRECATED as of PHP 7.2.0. Relying on this
function is highly discouraged.
Try this here code snippet here
$newfunc = create_function('$value', 'return urlencode(trim($value));');
$array=array_map($newfunc, $array);

Related

Does PHP declares variables passed to functions args by reference? [duplicate]

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 10 years ago.
I was trying to find this answer on Google, but I guess the symbol & works as some operator, or is just not generally a searchable term for any reason.. anyhow. I saw this code snippet while learning how to create WordPress plugins, so I just need to know what the & means when it precedes a variable that holds a class object.
//Actions and Filters
if (isset($dl_pluginSeries)) {
//Actions
add_action('wp_head', array(&$dl_pluginSeries, 'addHeaderCode'), 1);
//Filters
add_filter('the_content', array(&$dl_pluginSeries, 'addContent'));
}
This will force the variable to be passed by reference. Normally, a hard copy would be created for simple types. This can come handy for large strings (performance gain) or if you want to manipulate the variable without using the return statement, eg:
$a = 1;
function inc(&$input)
{
$input++;
}
inc($a);
echo $a; // 2
Objects will be passed by reference automatically.
If you like to handle a copy over to a function, use
clone $object;
Then, the original object is not altered, eg:
$a = new Obj;
$a->prop = 1;
$b = clone $a;
$b->prop = 2; // $a->prop remains at 1
The ampersand preceding a variable represents a reference to the original, instead of a copy or just the value.
See here: http://www.phpreferencebook.com/samples/php-pass-by-reference/
This passes something by reference instead of value.
See:
http://php.net/manual/en/language.references.php
http://php.net/manual/en/language.references.pass.php
I used it for sending a variable to a function, and have the function change the variable around. After the function is done, I don't need to return the function to the return value and set the new value to my variable.
Example
function fixString(&$str) {
$str = "World";
}
$str = "Hello";
fixString($str);
echo $str; //Outputs World;
Code without the &
function fixString($str) {
$str = "World";
return $str;
}
$str = "Hello";
$str = fixString($str);
echo $str; //Outputs World;

selecting array for array_push using Ternary Operator [duplicate]

This question already has an answer here:
Assigning variables by reference and ternary operator?
(1 answer)
Closed 1 year ago.
I have two arrays and I want to append to one or another based on a certain condition. The problem is that the array_push function should be called inside cases of a switch case inside a foreach loop, so using if-else means 20 extra lines of code. I thought I could do this using the Ternary Operator, but for some reason it doesn't work.
$arr1 = ['1', '2'];
$arr2 = ['a', 'b'];
$condition = False;
array_push($condition ? $arr1 : $arr2, 'new');
which produces this error:
array_push(): Argument #1 ($array) cannot be passed by reference
I thought $arr1 and $arr2 are references, and therefore you should be able to pass them, but something is not as it should be. At least that's how it behaves in C.
Have a look at the function signature for array_push():
array_push(array &$array, mixed ...$values): int
Notice the & in the first argument. That indicates that a reference must be passed.
Only variables can be passed by reference. A ternary expression is, well, an expression.
If you want to do this, you will need to first establish the reference, then pass it. And there's no easy way to shortcut that.
if( $condition) $ref = &$arr1; else $ref = &$arr2;
array_push($ref, 'new');
$ref = null; // clear reference

Passing the Values of an array to a function (not the array itself) [duplicate]

Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:
args = [3, 6]
range(*args) # call with arguments unpacked from a list
This is equivalent to:
range(3, 6)
Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP?
In php5.6 Argument unpacking via ... (splat operator) has been added. Using it, you can get rid of call_user_func_array() for this simpler alternative. For example having a function:
function add($a, $b){
return $a + $b;
}
With your array $list = [4, 6]; (after php5.5 you can declare arrays in this way).
You can call your function with ...:
echo add(...$list);
You can use call_user_func_array() to achieve that:
call_user_func_array("range", $args); to use your example.
In certain scenarios, you might consider using unpacking, which is possible in php, is a similar way to python:
list($min, $max) = [3, 6];
range($min, $max);
This is how I have arrived to this answer at least.
Google search: PHP argument unpacking
You should use the call_user_func_array
call_user_func_array(array(CLASS, METHOD), array(arg1, arg2, ....))
http://www.php.net/call_user_func_array
or use the reflection api http://www.php.net/oop5.reflection
<?php
function add(int ...$arr) { // typehint ready
return array_sum($arr);
}
var_dump(add(1, 2, 3, ...[1, 2, 3])); // int(12)
Another example with ... - operator.
RFC: https://wiki.php.net/rfc/variadics

Get value from PHP SimpleXMLElement object ([0] => value) [duplicate]

This question already has answers here:
Forcing a SimpleXML Object to a string, regardless of context
(11 answers)
Closed 2 years ago.
$value = $simpleXmlDoc->SomeNode->InnerNode;
actually assigns a simplexml object to $value instead of the actual value of InnerNode.
If I do:
$value = $simpleXmlDoc->SomeNode->InnerNode . "\n";
I get the value. Anyway of getting the actual value without the clumsy looking . "\n"?
Cast as whatever type you want (and makes sense...). By concatenating, you're implicitly casting to string, so
$value = (string) $xml->someNode->innerNode;
You don't have to specify innerNode.
$value = (string) $simpleXmlDoc->SomeNode;
What about using a typecast, like something like that :
$value = (string)$simpleXmlDoc->SomeNode->InnerNode;
See : type-juggling
Or you can probably use strval(), intval() and all that -- just probably slower, because of the function call.
Either cast it to a string, or use it in a string context:
$value = (string) $simpleXmlDoc->SomeNode->InnerNode;
// OR
echo $simpleXmlDoc->SomeNode->InnerNode;
See the SimpleXML reference functions guide

PHP callback using a reference [duplicate]

This question already has answers here:
Why does PHP's call_user_func() function not support passing by reference?
(4 answers)
Closed 8 years ago.
I have:
function increment(&$var)
{
$var++;
}
$a = 0;
call_user_func('increment', $a);
echo $a."\n";
Why does this return:
Warning: Parameter 1 to increment() expected to be a reference, value given in
and $a is still 0. Why is this?
Any references to official documentation would help.
Documentation says "Note: Note that the parameters for call_user_func() are not passed by reference."
You might use call_user_func_array instead.
function increment(&$a) {
$a++;
}
$x = 1;
call_user_func_array("increment", array(&$x));
echo $x;
From the documentation of call_user_func:
Calls the callback given by the first parameter and passes the remaining parameters as arguments.
This is what you want using call_user_func_array instead of call_user_func:
<?php
function increment(&$var)
{
$var++;
}
$a = 0;
call_user_func_array("increment", array(&$a));
echo $a."\n";

Categories