echo vsprintf('%s', 'word');
According to manual, second parameter for vsprintf() function must be array.
But this works, its normal? this may cause some error sometime?
The $args argument is automatically cast to an array:
$args = (array)$args; // = array('word');
Related
I am trying to create a PHP function with 2 parameters. One parameter is a variable and the second is an array like this
<?php
function Myfunction($variable, $array=array()){
foreach($array as $item){
echo $variable;
echo $item;
}
}
?>
I want a call like this:
<?php
Myfunction(blue, 1,3,6,10,5);
?>
"blue" is the variable
"numbers" insert in an array.
I tried something but it does not work.
Who can help me with this?
Well, there are two possibilities:
You can wrap your values in an array (ie: []), which I believe is what you intended:
Myfunction(blue, [1,3,6,10,5]);
Or you could take advantage of PHP's variable argument list and have your function parameters listed like so:
Myfunction($variable, ...$array);
Note the ... before $array, this signifies that this parameter will accept a variable number of arguments. Keep in mind that parameter using ... must be the last parameter in your argument list.
With this, you may call your function like so:
Myfunction(blue, 1,3,6,10,5);
Hope this helps,
As someone who is learning PHP I was experimenting with the arrap_map function. I was hoping that it would pass the same 3rd arg each time through to the called function. As below, this is not the behaviour of array_map. Is there an alternative function I can use to achieve this?
$arr = [['a'], ['b'], ['c']];
$args = ['set'];
function mapper($item, $arg){
return $item[] = $arg;
}
$result = array_map('mapper', $arr, $args);
only the first element has 'set' as a value
$arr = [['a'], ['b'], ['c']];
$args = ['set', 'set', 'set'];
function mapper($item, $arg){
return $item[] = $arg;
}
$result = array_map('mapper', $arr, $args);
all three elements have 'set' as a value
Your code is incorrect, $a[$b] doesn't make any sense. Both variables are strings.
Your output also doesn't make sense, quoting from the manual:
If more than one argument is passed then the returned array always has
integer keys.
To answer your question, it's a language design choice.
It could
pass NULL for missing elements (that was PHP does).
throw an error if the inputs don't have the same size.
cycle the smaller inputs.
All these have valid applications and their own problems.
option 1:
<?php
function hookRequest($func, $params = array()){
var_dump($func);
var_dump($params);
}
hookRequest('func1', array('param1', 'param2'));
option 2:
<?php
function hookRequest($func, $params){
var_dump($func);
var_dump($params);
}
hookRequest('func1', array('param1', 'param2'));
Question:
Both of above scripts can work. But I saw some scripts use this way: $params = array(), so just want to find out what is the difference between $params = array() and $params ?
If you don't pass anything into option1
hookRequest('func1');
then the $params is now an empty array.
function foobar($something,$foo = 'var')
{
var_dump($something,$foo);
}
foobar('something');
Output:
string(9) "something" string(3) "var"
Have a look on the "Function Arguments" basics in
http://php.net/manual/en/functions.arguments.php
The difference is that option 1 makes the second parameter optional, so that you can leave out the second option and the default value will be given to $param.
Option 2 makes the second parameter required, and will return a warning if you don't provide at least two parameters, e.g.
Warning: Missing argument 2 for hookRequest
It's called default parameters in PHP.
When you declare your function, hookRequest($func, $params = array()){... the $paramas = array() tell it to set it as an array when the passed parameter is blank.
I am having situation where i want to pass variables in php function.
The number of arguments are indefinite. I have to pass in the function without using the array.
Just like normal approach. Comma Separated.
like test(argum1,argum2,argum3.....,..,,.,.,.....);
How i will call the function? Suppose i have an array array(1,2,3,4,5) containing 5 parameters. i want to call the function like func(1,2,3,4,5) . But the question is that, How i will run the loop of arguments , When calling the function. I tried func(implode(',',array)); But it is taking all return string as a one parameters
In the definition, I also want the same format.
I can pass variable number of arguments via array but i have to pass comma separated.
I have to pass comma separated. But at the time of passing i don't know the number of arguments , They are in array.
At the calling side, use call_user_func_array.
Inside the function, use func_get_args.
Since this way you're just turning an array into arguments into an array, I doubt the wisdom of this though. Either function is fine if you have an unknown number of parameters either when calling or receiving. If it's dynamic on both ends, why not just pass the array directly?!
you can use :
$function_args = func_get_args();
inside your test() function definition .
You can just define your function as
function test ()
then use the func_get_args function in php.
Then you can deal with the arguments as an array.
Example
function reverseConcat(){
return implode (" ", array_reverse(func_get_args()));
}
echo reverseConcat("World", "Hello"); // echos Hello World
If you truely want to deal with them as though they where named parameters you could do something like this.
function getDistance(){
$params = array("x1", "y1", "x2", "y2");
$args = func_get_args();
// trim excess params
if (count($args) > count($params) {
$args = array_slice(0, count($params));
} elseif (count($args) < count($params)){
// define missing parameters as empty string
$args = array_pad($args, count($params), "");
}
extract (array_combine($params, $args));
return sqrt(pow(abs($x1-$x2),2) + pow(abs($y1-$y2),2));
}
use this function:
function test() {
$args = func_get_args();
foreach ($args as $arg) {
echo "Arg: $arg\n";
}
}
I'm not sure what you mean by "same format." Do you mean same type, like they all have to be a string? Or do you mean they need to all have to meet some criteria, like if it's a list of phone numbers they need to be (ddd) ddd-dddd?
If it's the latter, you'll have just as much trouble with pre-defined arguments, so I'll assume you mean you want them all to be the same type.
So, going off of the already suggested solution of using func_get_args(), I would also apply array_filter() to ensure the type:
function set_names() {
function string_only($arg) {
return(is_string($arg));
}
$names_provided = func_get_args();
// Now you have an array of the args provided
$names_provided_clean = array_filter($names_provided, "string_only");
// This pulls out any non-string args
$names = array_values($names_provided_clean);
// Because array_filter doesn't reindex, this will reset numbering for array.
foreach($names as $name) {
echo $name;
echo PHP_EOL;
}
}
set_names("Joe", "Bill", 45, array(1,2,3), "Jane");
Notice that I don't do any deeper sanity-checks, so there could be issues if no values are passed in, etc.
You can use array also using explode http://www.php.net/manual/en/function.explode.php.
$separator = ",";
$prepareArray = explode ( $separator , '$argum1,$argum2,$argum3');
but be careful, $argum1,$argum2, etc should not contain , in value. You can overcome this by adding any separator. $separator = "VeryUniqueSeparator";
I don't have code so can't tell exact code. But manipulating this will work as your requirements.
I'm trying to use empty() in array mapping in php. I'm getting errors that it's not a valid callback.
$ cat test.php
<?
$arrays = array(
'arrEmpty' => array(
'','',''
),
);
foreach ( $arrays as $key => $array ) {
echo $key . "\n";
echo array_reduce( $array, "empty" );
var_dump( array_map("empty", $array) );
echo "\n\n";
}
$ php test.php
arrEmpty
Warning: array_reduce(): The second argument, 'empty', should be a valid callback in /var/www/authentication_class/test.php on line 12
Warning: array_map(): The first argument, 'empty', should be either NULL or a valid callback in /var/www/authentication_class/test.php on line 13
NULL
Shouldn't this work?
Long story: I'm trying to be (too?) clever and checking that all array values are not empty strings.
It's because empty is a language construct and not a function. From the manual on empty():
Note: Because this is a language construct and not a function, it cannot be called using variable functions
Try array_filter with no callback instead:
If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.
You can then use count(array_filter($array)) to see if it still has values.
Or simply wrap empty into a callable, like this:
array_reduce($array, create_function('$x', 'return empty($x);'));
or as of PHP 5.3
array_reduce($array, function($x) { return empty($x); });
To add to the others, it's common for PHP developers to create a function like this:
function isEmpty($var)
{
return empty($var);
}
Empty can't be used as a callback, it needs to operate on a variable. From the manual:
Note: empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).
I don't know why, somehow empty() worked for me inside a callback.
The reason why I was originally getting this error was because I was trying to callback as an independent function, whereas it was inside my class and I had to call it using array(&$this ,'func_name')
See code below. It works for me. I am php 5.2.8, if that matters...
$table_values = array_filter( $table_values, array(&$this, 'remove_blank_rows') );
function remove_blank_rows($row){
$not_blank = false;
foreach($row as $col){
$cell_value = trim($col);
if(!empty( $cell_value )) {
$not_blank = true;
break;
}
}
return $not_blank;
}