Getting the function arguments in javascript like in PHP [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calling dynamic function with dynamic parameters in Javascript
javascript array parameter list
I'm looking for the Javascript equivalent of the following functionality I use in PHP:
function myfunc()
{
$arg_arr = array();
$arg_arr = func_get_args();
$my_arg_val_1 = (!isset($arg_arr[1]) || ($arg_arr[1] == '')) ? true : $arg_arr[1];
}
Basically, I'm trying to get the function arguments. I want to write a javascript function to take one argument, but I want to add some code to do a few things with the second and third argument if it is provided, but I'm not sure how to pull this off.
Any assistance will be appreciated.
Thanks.

Use the arguments variable.
It's not an array (it's an "Array-like object", which has a few differences with a standard array), but you can convert it to a real array this way :
function myfunc() {
var argArray = Array.prototype.slice.call( arguments );
/* ... do whatever you want */
}

In JavaScript there is arguments variable available in each function. It looks like an array which contains all arguments passed to a function:
function myfunc() {
var arg1 = arguments[0],
arg2 = arguments[1],
argc = arguments.length;
}
myfunc(1, "abc"); // arg1 = 1,
// arg2 = "abc",
// argc = 2

This question is a dupe, but the answer is straightforward:
function foo() {
for (var i = 0; i < arguments.length; i++) {
alert(arguments[i]);
}
}

Those function you have been ported to js:
func_get_arg
func_get_args
isset
array
{php} .js

Related

Undefined variable using function into function [duplicate]

This question already has answers here:
PHP variables in anonymous functions
(2 answers)
Closed 6 years ago.
I have an issue using this code in order to get the appropriate result.
My code:
function check_txt($url, $content) {
global $content;
$result = get_file_contents($url);
$arr = array_filter($result, function($ar) {
return ($ar['txt'] == $content);
});
return $arr[0];
}
I got this error when I execute the code:
Notice: Undefined variable: content in myfile.php
My question is how to pass content variable to function($ar) ? already tried function($ar, $content) and too global $content; like the code I posted.
You need to USE the $content variable assuming it is actually available, to make it available in your annonymous function
function check_txt($url, $content) {
$result = get_file_contents($url);
$arr = array_filter($result, function($ar) use ($content) {
return ($ar['txt'] == $content);
});
return $arr[0];
}
The Manual has more details and examples
Either
A) if you have $content previously defined in global scope, use the global you have and remove the $content parameter.
or,
B) remove the global declaration and pass something in using the $content parameter.
PS: As others have pointed out, you need to use a use() on the anon function... but also pass param or go global, don't do both.
The array_filter() function filters the values of an array using a callback function.
This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.
http://www.w3schools.com/php/func_array_filter.asp
Hope this helps :)

How to call PHP function from string stored in a Variable with arguments [duplicate]

This question already has answers here:
How to call a function from a string stored in a variable?
(18 answers)
Closed 1 year ago.
I found question from here. But I need to call function name with argument.
I need to be able to call a function, but the function name is stored in a variable, is this possible? e.g:
function foo ($argument)
{
//code here
}
function bar ($argument)
{
//code here
}
$functionName = "foo";
$functionName($argument);//Call here foo function with argument
// i need to call the function based on what is $functionName
Anyhelp would be appreciate.
Wow one doesn't expect such a question from a user with 4 golds. Your code already works
<?php
function foo ($argument)
{
echo $argument;
}
function bar ($argument)
{
//code here
}
$functionName = "foo";
$argument="Joke";
$functionName($argument); // works already, might as well have tried :)
?>
Output
Joke
Fiddle
Now on to a bit of theory, such functions are called Variable Functions
PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.
If you want to call a function dynamically with argument then you can try like this :
function foo ($argument)
{
//code here
}
call_user_func('foo', "argument"); // php library funtion
Hope it helps you.
you can use the php function call_user_func.
function foo($argument)
{
echo $argument;
}
$functionName = "foo";
$argument = "bar";
call_user_func($functionName, $argument);
if you are in a class, you can use call_user_func_array:
//pass as first parameter an array with the object, in this case the class itself ($this) and the function name
call_user_func_array(array($this, $functionName), array($argument1, $argument2));

PHP: Use result of anonymous function directly as string? [duplicate]

This question already has answers here:
How do I immediately execute an anonymous function in PHP?
(9 answers)
Closed 10 years ago.
Is it possible to do something like this. Lets say we have a function that accepts string as argument. But to provide this string we have to do some processing of data. So I decided to use closures, much like in JS:
function i_accept_str($str) {
// do something with str
}
$someOutsideScopeVar = array(1,2,3);
i_accept_str((function() {
// do stuff with the $someOutsideScopeVar
$result = implode(',', $someOutsideScopeVar); // this is silly example
return $result;
})());
The idea is to when calling i_accept_str() to be able to directly supply it string result... I probably can do it with call_user_func which is known to be ineffective but are there alternatives?
Both PHP 5.3 and PHP 5.4 solutions are accepted (the above wanted behavior is tested and does not work on PHP 5.3, might work on PHP 5.4 though...).
In PHP (>=5.3.0, tested with 5.4.6) you have to use call_user_func and import Variables from the outer Scope with use.
<?php
function i_accept_str($str) {
// do something with str
echo $str;
}
$someOutsideScopeVar = array(1,2,3);
i_accept_str(call_user_func(function() use ($someOutsideScopeVar) {
// do stuff with the $someOutsideScopeVar
$result = implode(',', $someOutsideScopeVar); // this is silly example
return $result;
}));

php - many optional parameters [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Any way to specify optional parameter values in PHP?
PHP function - ignore some default parameters
Suppose I have function like this:
function foo($name = "john", $surname = "smith") { ... }
And I am calling like this:
$test = foo("abc", "def");
Imagine now that I would like to skip the name and only use the surname, how is that achievable? If I only do $test = foo("def"); how can the compiler know I am referring to the surname and not to the name? I understand it could be done by passing NULL, but I need this for something more like this:
$test = foo($_POST['name'], $_POST['surname']);
Thanks in advance.
You can try this-
$num_args = func_num_args();
if($num_args == 1)
$surname = func_get_arg(1);
else
$surname = func_get_arg(2);
$name = func_get_arg(1);
Please test it before you use it.
Your code
$test = foo($_POST['name'], $_POST['surname']);
will also pass NULL in the first PARAMETER if it is empty so the compiler will know that it is up to the second parameter. Having a comma in the parameter list will already inform PHP that there are two parameters here.
You can do so by passing an empty string to your function and detecting in your function if the passed argument is an empty string, and if it is, then replacing it by the default value. this would make your function call like:
foo('','lastname');
And you can add these few lines to beginning of your function to detect if an empty string has been passed as a parameter:
function foo($name = "john", $surname = "smith") {
if($name==='') { $name = 'john'}
//more code
... }
I usually do something like so:
function foo($parameters = array())
{
print_r($parameters);
}
foo($_POST); //will output the array
It's what I use, when I expect more than 3 parameters.
But you might as well use the following:
function foo()
{
$args = func_get_args();
foreach ($args as $arg) {
echo "$arg \n";
}
}

Two different return types in PHP function [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Multiple returns from function
Is it possible to return 2 results in the same PHP function? One is an array, the other is an integer. Could someone give me an example?
function functest() {
return array(1, "two");
}
list($first,$second) = functest();
There's nothing stopping you from returning whatever type you like from a function. You can return a dictionary with multiple keys, or an array of mixed object types, or whatever. Anything you like.
$arr = array();
$arr[] = $some_object;
$arr[] = 3;
$arr["a_string"] = "foo";
return $arr;
You have several options to simulate multiple return values (the first two, however, are just a kind of wrapping of multiple values into one):
Return an array with the two values: return array($myInt, $myArr); (see e.g. parse_url().)
Create a dedicated wrapper object and return this: return new MyIntAndArrayWrapper($myInt, $myArr);
Add an "output argument" to the function signature: function myFunc(&$myIntRetVal) { ... return $myArr; } (see e.g. preg_match(..., &$matches).)
What about this?
function myfunction() {
//Calculate first result
$arrayresult=...
//Calculate second result
$intresult=...
//Move in with each other . don't be shy!
return array($arrayresult,$intresult)
}
and in the other code
$tmp=myfunction();
$arrayresult=$tmp[0];
$intresult=$tmp[1];
It's totally possible since PHP doesn't use strong typing. Just return the value you want in whatever type you want. A simple example:
function dual($type) {
if ($type === 'integer')
return 4711;
else
return 'foo';
}
You can use several functions on the caller side to see which type you got, for example: gettype, is_int, is_a.

Categories