Empty array after passing array by reference to array_walk() - php

I have made this little class:
class Analyzer {
public static function analyze($phrases) {
$sortedPhrases = array();
array_walk($phrases, array('self', 'splitByLength'), $sortedPhrases);
var_dump($sortedPhrases);
}
private static function splitByLength($item, $key, &$resArr) {
// line stolen from here: http://stackoverflow.com/a/4786840/603003
// thanks to arnaud576875 <http://stackoverflow.com/users/576875/arnaud576875>
$len = count( preg_split('#\PL+#u', $item, -1, PREG_SPLIT_NO_EMPTY) );
if (!isset($resArr[$len])) {
$resArr[$len] = array();
}
$resArr[$len][] = $item;
var_dump($resArr);
}
}
$phrases = array(
"I can't believe the great content",
"I can't understand the superior information",
"I can't comprehend the amazing data",
"I cannot analyze the amazing data",
"I haven't written to the amazing data"
);
Analyzer::analyze($phrases);
Executing the script results in the output below:
array (size=1)
7 =>
array (size=1)
0 => string 'I can't believe the great content' (length=33)
...
array (size=3)
7 =>
array (size=3)
0 => string 'I can't believe the great content' (length=33)
1 => string 'I can't understand the superior information' (length=43)
2 => string 'I can't comprehend the amazing data' (length=35)
6 =>
array (size=1)
0 => string 'I cannot analyze the amazing data' (length=33)
8 =>
array (size=1)
0 => string 'I haven't written to the amazing data' (length=37)
array (size=0)
empty
All outputs are actually correct except the last one which comes from Analyzer::analyze(). It seems that the variable $sortedPhrases is somehow cleared after array_walk().

Take a better look at array_walk's documentation page.
userdata
If the optional userdata parameter is supplied, it will be passed as
the third parameter to the callback funcname.
That's the third parameter. It's not a reference, it's just a value that gets passed to your callback function.
One (of many) solutions to your problem is to use an object instead (objects are always passed by reference):
class Analyzer {
public static function analyze($phrases) {
$arrObj = new ArrayObject();
array_walk($phrases, array('self', 'splitByLength'), $arrObj);
var_dump($arrObj->getArrayCopy());
}
private static function splitByLength($item, $key, $arrObj) {
// line stolen from here: http://stackoverflow.com/a/4786840/603003
// thanks to arnaud576875 <http://stackoverflow.com/users/576875/arnaud576875>
$len = count( preg_split('#\PL+#u', $item, -1, PREG_SPLIT_NO_EMPTY) );
if (!isset($arrObj[$len])) {
$arrObj[$len] = array();
}
$arrObj[$len][] = $item;
var_dump($arrObj->getArrayCopy());
}
}
(it doesn't have to be an ArrayObject, it can be a stdClass object with an array property, or create your own class if you want...)
Or you can wrap your call within an anonymous function if you really want to work with a reference:
$static = get_called_class();
array_walk($phrases, function($item, $key) use($static, &$sortedPhrases){
$static::splitByLength($item, $key, $sortedPhrases);
});

While the third argument sent to the callback function cannot be a reference itself, it can contain references.
A different approach (to using objects or wrapping your callback in a closure) is to pass an array to the callback, containing a reference to the variable you wish to update. The wrapping array gets passed by-value, but all it contains is the referenced value that you want to change.
class Analyzer {
public static function analyze($phrases) {
// …
array_walk($phrases,
array('self', 'splitByLength'),
array(&$sortedPhrases));
// …
}
private static function splitByLength($item, $key, $extra_args) {
$resArr = &$extra_args[0];
// …
}
}

Pretty sure this is wrong:
array_walk($phrases, array('self', 'splitByLength'), $sortedPhrases);
So, Try this:
$sortedPhrases = array_walk($phrases, 'splitByLength');
And return your values in $sortedPhrases and don't use pass by reference (personal thing)

Related

pass value for last default parameter of function

From very long time i am working on php.
But one question may I have no idea about
like I have one function as bellow:
function hello($param1, $param2="2", $param3="3", $param4="4")
Now whenever I will use this function and if I need 4th params thats the $param4 then still I need to call all as blank like this one:
hello(1, '', '', "param4");
So is there any another way to just pass 1st and 4th param in call rather then long list of blanks ?
Or is there any other standard way for this ?
There was an RFC for this named skipparams but it was declined.
PHP has no syntactic sugar such as hello(1, , , "param4"); nor hello(1, default, default, "param4"); (per the RFC) for skipping optional parameters when calling a function.
If this is your own function then you can choose the common jQuery style of passing options into plug-ins like this:
function hello( $param1, $more_params = [] )
{
static $default_params = [
'param2' => '2',
'param3' => '3',
'param4' => '4'
];
$more_params = array_merge( $default_params, $more_params );
}
Now you can:
hello( 1, [ 'param4'=>'not 4, muahaha!' ] );
If your function requires some advanced stuff such as type hinting then instead of array_merge() you will need to manually loop $more_params and enforce the types.
One potential way you can do this, while a little bit hacky, may work well in some situations.
Instead of passing multiple variables, pass a single array variable, and inside the function check if the specific keys exist.
function hello($param1, $variables = ["param2" => "2", "param3" => "3", "param4" => "4"]) {
if(!array_key_exists("param2", $variables)) $variables['param2'] = "2";
if(!array_key_exists("param3", $variables)) $variables['param3'] = "3";
if(!array_key_exists("param4", $variables)) $variables['param4'] = "4";
echo "<pre>".print_r($variables, true)."</pre>";
}
This will allow you to set "param4" in the above variable, while still remaining default on all of the others.
Calling the function this way:
hello("test", ["param4" => "filling in variable 4"]);
Will result in the output being:
Array
(
[param4] => filling in variable 4
[param2] => 2
[param3] => 3
)
I don't generally recommend this if it can be avoided, but if you absolutely need this functionality, this may work for you.
The key here is that you have a specifically named index inside the array being passed, that you can check against inside the function itself.
The answer, as I see it, is yes and no.
No, because there's no way to do this in a standard fashion.
Yes, because you can hack around it. This is hacky, but it works ;)
Example:
function some_call($parm1, $parm2='', $parm3='', $parm4='') { ... }
and the sauce:
function some_call_4($parm1, $parm4) {
return some_call($parm1, '', '', $parm4);
}
So if you make that call ALOT and are tired of typing it out, you can just hack around it.
Sorry, that's all I've got for you.
It is an overhead, but you can use ReflectionFunction to create a class, instance of which that can be invoked with named parameters:
final class FunctionWithNamedParams
{
private $func;
public function __construct($func)
{
$this->func = $func;
}
public function __invoke($params = [])
{
return ($this->func)(...$this->resolveParams($params));
}
private function resolveParams($params)
{
$rf = new ReflectionFunction($this->func);
return array_reduce(
$rf->getParameters(),
function ($carry, $param) use ($params) {
if (isset($params[$param->getName()])) {
$carry[] = $params[$param->getName()];
} else if ($param->isDefaultValueAvailable()) {
$carry[] = $param->getDefaultValue();
} else {
throw new BadFunctionCallException;
}
return $carry;
},
[]
);
}
}
Then you can use it like this:
function hello($param1, $param2 = "2", $param3 = "3", $param4 = "4")
{
var_dump($param1, $param2, $param3, $param4);
}
$func = new FunctionWithNamedParams('hello');
$func(['param1' => '1', 'param4' => 'foo']);
Here is the demo.

Passing parameter to a function by parameter name? [duplicate]

Is it possible in PHP to specify a named optional parameter when calling a function/method, skipping the ones you don't want to specify (like in python)?
Something like:
function foo($a, $b = '', $c = '') {
// whatever
}
foo("hello", $c="bar"); // we want $b as the default, but specify $c
No, it is not possible (before PHP 8.0): if you want to pass the third parameter, you have to pass the second one. And named parameters are not possible either.
A "solution" would be to use only one parameter, an array, and always pass it... But don't always define everything in it.
For instance :
function foo($params) {
var_dump($params);
}
And calling it this way : (Key / value array)
foo([
'a' => 'hello',
]);
foo([
'a' => 'hello',
'c' => 'glop',
]);
foo([
'a' => 'hello',
'test' => 'another one',
]);
Will get you this output :
array
'a' => string 'hello' (length=5)
array
'a' => string 'hello' (length=5)
'c' => string 'glop' (length=4)
array
'a' => string 'hello' (length=5)
'test' => string 'another one' (length=11)
But I don't really like this solution :
You will lose the phpdoc
Your IDE will not be able to provide any hint anymore... Which is bad
So I'd go with this only in very specific cases -- for functions with lots of optional parameters, for instance...
PHP 8 was released on November 26, 2020 with a new feature called named arguments.
In this major version release, "named parameters" (aka "named arguments") afford developers some really cool new techniques when calling native and custom functions.
The custom function in this question can now be called with the first parameter (because there is no default for it) and then only the third parameter passed by using named parameters like this: (Demo)
function foo($a, $b = '', $c = '') {
echo $a . '&' . $b . '&' . $c;
}
foo("hello", c: "bar");
// output: hello&&bar
Notice that the second parameter did not need to be declared in the function call because it has a default value defined -- the default value is automatically used within the function body.
Part of the beauty of this new feature is that you don't need to be careful about the order of your named parameters -- the order of their declaration is irrelevant. foo(c: "bar", a: "hello"); works just the same. Having the ability to "skip" declarations and write declarative parameters will improve the readability of your scripts. The only downside of this new feature is that there will be a little bit more bloat in the function calls, but I (and many others) think the benefits outweigh this "cost".
Here is an example of a native function omitting the limit parameter, writing the parameters out of their normal order, and declaring a reference variable. (Demo)
echo preg_replace(
subject: 'Hello 7',
pattern: '/[a-z ]/',
count: $counted,
replacement: ''
)
. " & " . $counted;
// output: H7 & 5
There is more to tell about this new feature. You can even use an associative array to pass the named parameters to the function where the spread/splat operator can be used to unpack the data!
(*notice the slight difference in declaring the reference variable.) (Demo)
$params = [
'subject' => 'Hello 7', // normally third parameter
'pattern' => '/[a-z ]/', // normally first parameter
// 'limit' // normally fourth parameter, omitted for this demonstration; the default -1 will be used
'count' => &$counted, // normally fifth parameter
// ^-- don't forget to make it modifiable!
'replacement' => '', // normally second parameter
];
echo preg_replace(...$params) . " & " . $counted;
// same output as the previous snippet
For more information, here are a few leads that explain further about this feature and some common related errors: (I have no affiliation with the following sites)
https://wiki.php.net/rfc/named_params
https://stitcher.io/blog/php-8-named-arguments
https://stitcher.io/blog/why-we-need-named-params-in-php
No, PHP cannot pass arguments by name.
If you have a function that takes a lot of arguments and all of them have default values you can consider making the function accept an array of arguments instead:
function test (array $args) {
$defaults = array('a' => '', 'b' => '', 'c' => '');
$args = array_merge($defaults, array_intersect_key($args, $defaults));
list($a, $b, $c) = array_values($args);
// an alternative to list(): extract($args);
// you can now use $a, $b, $c
}
See it in action.
No, it isn't.
The only way you can somewhat do that is by using arrays with named keys and what not.
As of PHP 5.4 you have shorthand array syntax (not nessecary to specify arrays with cumbersome "array" and instead use "[]").
You can mimic named parameters in many ways, one good and simple way might be:
bar('one', ['a1' => 'two', 'bar' => 'three', 'foo' => 'four']);
// output: twothreefour
function bar ($a1, $kwargs = ['bar' => null, 'foo' => null]) {
extract($kwargs);
echo $a1;
echo $bar;
echo $foo;
}
You can keep the phpdoc and the ability to set defaults by passing an object instead of an array, e.g.
class FooOptions {
$opt1 = 'x';
$opt2 = 'y';
/* etc */
};
That also lets you do strict type checking in your function call, if you want to:
function foo (FooOptions $opts) {
...
}
Of course, you might pay for that with extra verbosity setting up the FooOptions object. There's no totally-free ride, unfortunately.
It's not exactly pretty, but it does the trick, some might say.
class NamedArguments {
static function init($args) {
$assoc = reset($args);
if (is_array($assoc)) {
$diff = array_diff(array_keys($assoc), array_keys($args));
if (empty($diff)) return $assoc;
trigger_error('Invalid parameters: '.join(',',$diff), E_USER_ERROR);
}
return array();
}
}
class Test {
public static function foobar($required, $optional1 = '', $optional2 = '') {
extract(NamedArguments::init(get_defined_vars()));
printf("required: %s, optional1: %s, optional2: %s\n", $required, $optional1, $optional2);
}
}
Test::foobar("required", "optional1", "optional2");
Test::foobar(array(
'required' => 'required',
'optional1' => 'optional1',
'optional2' => 'optional2'
));
Normally you can't but I think there a lot of ways to pass named arguments to a PHP function. Personally I relay on the definition using arrays and just call what I need to pass:
class Test{
public $a = false;
private $b = false;
public $c = false;
public $d = false;
public $e = false;
public function _factory(){
$args = func_get_args();
$args = $args[0];
$this->a = array_key_exists("a",$args) ? $args["a"] : 0;
$this->b = array_key_exists("b",$args) ? $args["b"] : 0;
$this->c = array_key_exists("c",$args) ? $args["c"] : 0;
$this->d = array_key_exists("d",$args) ? $args["d"] : 0;
$this->e = array_key_exists("e",$args) ? $args["e"] : 0;
}
public function show(){
var_dump($this);
}
}
$test = new Test();
$args["c"]=999;
$test->_factory($args);
$test->show();
live example here:
http://sandbox.onlinephpfunctions.com/code/d7f27c6e504737482d396cbd6cdf1cc118e8c1ff
If I have to pass 10 arguments, and 3 of them are the data I really need, is NOT EVEN SMART to pass into the function something like
return myfunction(false,false,10,false,false,"date",false,false,false,"desc");
With the approach I'm giving, you can setup any of the 10 arguments into an array:
$arr['count']=10;
$arr['type']="date";
$arr['order']="desc";
return myfunction($arr);
I have a post in my blog explaining this process in more details.
http://www.tbogard.com/2013/03/07/passing-named-arguments-to-a-function-in-php
With PHP, the order of arguments is what matters. You can't specify a particular argument out of place, but instead, you can skip arguments by passing a NULL, as long as you don't mind the value in your function having a NULL value.
foo("hello", NULL, "bar");
If you really really want, try the reflection.
And skip with null.
function getDefaultValueByNull($fn, $inputs) {
$ref = new ReflectionFunction($fn);
$args = array_map(function($p) {
return [
$p->getName(),
$p->isDefaultValueAvailable() ? $p->getDefaultValue() : NULL,
];
}, $ref->getParameters());
foreach($inputs as $i=>$val) { if ($val!==NULL) $args[$i][1] = $val; }
return array_column($args, 1, 0);
}
function sum($a=9, $b) {
extract(getDefaultValueByNull(__FUNCTION__, func_get_args()));
return $a+$b;
}
echo sum(NULL, 1); // 10
Here's what I've been using. A function definition takes one optional array argument which specifies the optional named arguments:
function func($arg, $options = Array()) {
$defaults = Array('foo' => 1.0,
'bar' => FALSE);
$options = array_merge($default, $options);
// Normal function body here. Use $options['foo'] and
// $options['bar'] to fetch named parameter values.
...
}
You can normally call without any named arguments:
func("xyzzy")
To specify an optional named argument, pass it in the optional array:
func("xyzzy", Array('foo' => 5.7))
No not really. There are a few alternatives to it you could use.
test(null,null,"hello")
Or pass an array:
test(array('c' => "hello"));
Then, the function could be:
function test($array) {
$c = isset($array[c]) ? $array[c] : '';
}
Or add a function in between, but i would not suggest this:
function ctest($c) { test('','',$c); }
I dont think so...
If you need to call, for example, the substr function, that has 3 params, and want to set the $length without set the $start, you'll be forced to do so.
substr($str,0,10);
a nice way to override this is to always use arrays for parameters
In very short, sometimes yes, by using reflection and typed variables. However I think this is probably not what you are after.
A better solution to your problem is probably to pass in the 3 arguments as functions handle the missing one inside your function yourself
<?php
function test(array $params)
{
//Check for nulls etc etc
$a = $params['a'];
$b = $params['b'];
...etc etc
}
You can't do it the python way. Anway, you could pass an associative array and than use the array entries by their name:
function test ($args=array('a'=>'','b'=>'','c'=>''))
{
// do something
}
test(array('c'=>'Hello'));
This doesn't reduce the typing, but at least it's more descriptive, having the arguments' names visible and readable in the call.
Here is a work around:
function set_param_defaults($params) {
foreach($params['default_values'] as $arg_name => $arg_value) {
if (!isset($params[$arg_name])) {
$params[$arg_name] = $arg_value;
}
}
return $params;
}
function foo($z, $x = null, $y = null) {
$default_values = ['x' => 'default value for x', 'y' => 'default value for y'];
$params = set_param_defaults(get_defined_vars());
print "$z\n";
print $params['x'] . "\n";
print $params['y'] . "\n";
}
foo('set z value', null, 'set y value');
print "\n";
foo('set z value', 'set x value');
ALTERNATIVELY:
Personally I would go with this method.
function foo($z, $x_y) {
$x_y += ['x' => 'default value for x', 'y' => 'default value for y'];
print "$z\n";
print $x_y['x'] . "\n";
print $x_y['y'] . "\n";
}
foo('set z value', ['y' => 'set y value']);
print "\n";
foo('set z value', ['x' => 'set x value']);
Print outs for both examples.
1st call:
set z value
default value for x
set y value
2nd call:
set z value
set x value
default value for y
Just use the associative array pattern Drupal uses. For optional defaulted arguments, just accept an $options argument which is an associative array. Then use the array + operator to set any missing keys in the array.
function foo ($a_required_parameter, $options = array()) {
$options += array(
'b' => '',
'c' => '',
);
// whatever
}
foo('a', array('c' => 'c’s value')); // No need to pass b when specifying c.

Function as array value

I can't seem to find anything of this, and was wondering if it's possible to store a function or function reference as a value for an array element. For e.g.
array("someFunc" => &x(), "anotherFunc" => $this->anotherFunc())
Thanks!
You can "reference" any function. A function reference is not a reference in the sense of "address in memory" or something. It's merely the name of the function.
<?php
$functions = array(
'regular' => 'strlen',
'class_function' => array('ClassName', 'functionName'),
'object_method' => array($object, 'methodName'),
'closure' => function($foo) {
return $foo;
},
);
// while this works
$functions['regular']();
// this doesn't
$functions['class_function']();
// to make this work across the board, you'll need either
call_user_func($functions['object_method'], $arg1, $arg2, $arg3);
// or
call_user_func_array($functions['object_method'], array($arg1, $arg2, $arg3));
PHP supports the concept of variable functions, so you can do something like this:
function foo() { echo "bar"; }
$array = array('fun' => 'foo');
$array['fun']();
Yout can check more examples in manual.
Yes, you can:
$array = array(
'func' => function($var) { return $var * 2; },
);
var_dump($array['func'](2));
This does, of course, require PHP anonymous function support, which arrived with PHP version 5.3.0. This is going to leave you with quite unreadable code though.
check out PHP's call_user_func. consider the below example.
consider two functions
function a($param)
{
return $param;
}
function b($param)
{
return $param;
}
$array = array('a' => 'first function param', 'b' => 'second function param');
now if you want to execute all the function in a sequence you can do it with a loop.
foreach($array as $functionName => $param) {
call_user_func($functioName, $param);
}
plus array can hold any data type, be it function call, nested arrays, object, string, integer etc. etc.

strip null values of json object

All my AJAX requests are in json format which are being parsed in javascript.
How can i prevent null values being displayed in an HTML page without needing to write an if-statement in javascript for each json value?
Or should i write a custom PHP function to encode an array to json instead of using json_encode() so it doesn't display 'null' ?
In server side with PHP,
You can use array_filter before json_encode.
array_filter without second argument removes null elements of entry array, example :
$object= array(
0 => 'foo',
1 => false,
2 => -1,
3 => null,
4 => ''
);
$object = (object) array_filter((array) $object);
$result = json_encode($object);
The $result contains:
{"0":"foo","2":-1}
As you see, the null elements are removed.
I'm going to add to the accepted answer because that will only work if you have a 1 dimensional object or array. If there is any array or object nesting then in order to get the accepted solution to work, you must create some sort of recursive array filter. Not ideal.
The best solution my colleague and I came up with was to actually perform a regular expression on the JSON string before it was returned from the server.
$json = json_encode($complexObject);
echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $json);
The regular expression will remove all places in the string of the form ,"key":null including any whitespace between the leading comma and the start of the key. It will also match "key":null, afterwards to make sure that no null values were found at the beginning of a JSON object.
This isn't an ideal solution but it's far better than creating a recursive array filter given an object could be several dimensions deep. A better solution would be if json_encode had a flag that let you specify if you wanted null entries to remain in the output string.
To remove only NULL, but keep FALSE, '', and 0:
function is_not_null($var)
{
return !is_null($var);
}
echo json_encode(array_filter((array) $object, 'is_not_null'));
public function __toString() {
$obj = clone $this;
$keys = get_object_vars($obj);
foreach ($keys as $key => $value) {
if (!$value) {
unset($obj->{$key});
}
}
return json_encode($obj);
}
What about using the native JSON.stringify method on the javascript side?
You can set, a second parameter, a function to remove keys with a null value.
If you return undefined, the property is not included in the output JSON string (check the documentation for "the replacer parameter" at https://developer.mozilla.org/en-US/docs/Using_native_JSON#The_replacer_parameter).
function removeNulls(obj) {
var str = JSON.stringify(obj, function(key, val) {
if (val == null) return undefined;
return val;
});
return JSON.parse(str);
}
Then you can have a "normalized" JSON object by calling:
var obj = removeNulls(obj);
echo json_encode(array_filter((array) $object, function($val) {
return !empty($val);
}));
class Foo implements JsonSerializable
{
public $param1;
public $param2;
public function jsonSerialize()
{
return array_filter((array) $this, function ($var) {
return !is_null($var);
});
}
}
public function testJsonSerialization()
{
$expectedJson = '{"param1":true}';
$foo = new Foo();
$foo->param1 = true;
$foo->param2 = null;
$this->assertEquals(
$expectedJson,
json_encode($foo)
);
}`
of course you can create Abstract class with custom jsonSerialize method and extend all your DTOs from this
A version that works with multi-dimensional arrays.
$withoutNull = function($a) use (&$withoutNull) {
return array_filter(
array_map(
fn($p) => is_array($p) ? $withoutNull($p) : $p, $a
)
);
};
Example:
$a = [
"name" => "nathan",
"data" => [
"age" => 27,
"something" => null
],
"another" => null
];
$b = $withoutNull($a);
print_r($b);
Output:
Array
(
[name] => nathan
[data] => Array
(
[age] => 27
)
)

What is the syntax for multiple arguments in PHP?

A simple question:
What is the syntax for creating a function with unlimited* arguments in PHP?
Example (ActionScript 3):
function multiTrace(...arguments):void
{
var i:String;
for each(i in arguments)
trace(i);
}
The goal is to have a function that I can call and list any given amount of stylesheets within, eg:
$avian->insertStyles("overall.css", "home.css");
*Subject to obvious limitations (RAM, etc).
function multiTrace()
{
$args = func_get_args();
while ($arg = array_shift($args)) {
echo $arg;
}
}
see: http://php.net/manual/en/function.func-get-args.php
See
http://nl.php.net/manual/en/function.func-get-args.php
function testfunction() {
$arguments = func_get_args();
var_dump($arguments);
}
testfunction("argument1", "argument2");
Result:
array
0 => string 'argument1' (length=9)
1 => string 'argument2' (length=9)
I think you are after the func_get_args function:
http://php.net/manual/en/function.func-get-args.php

Categories