php - many optional parameters [duplicate] - php

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";
}
}

Related

Easiest way to check if multiple POST parameters are set?

Hi so I want to know the easiest way to check if multiple POST parameters are set. Instead of doing a long if check with multiple "isset($_POST['example'])" linked together by "&&", I wanted to know if there was a cleaner way of doing it.
What I ended up doing was making an array and looping over it:
$params_needed = ["song_name", "artist_name", "song_release_date",
"song_genre", "song_medium"];
I would then call the function below, passing in $params_needed to check if the parameter names above are set:
function all_params_valid($params_needed) {
foreach ($params_needed as $param) {
if (!isset($_POST[$param])) {
error("Missing the " . $param . " variable in POST request.");
return false;
}
}
return true;
}
if (all_params_valid($params_needed)) {
$song_name = $_POST["song_name"];
$artist_name = $_POST["artist_name"];
$song_release_date = $_POST["song_release_date"];
$song_genre = $_POST["song_genre"];
$song_medium = $_POST["song_medium"];
...
}
However when I do this, it gets stuck on the first index and says "Missing the song_name variable..." despite actually including it in the POST request, and I'm not sure why this is happening. The expected behavior would be for it to move on and tell me the next parameter "artist_name" is not set, but this doesn't happen.
I personally like using array_diff for this issue.
PHP array_diff documentation
What you care about is your expected input is the same as the given input.
So you can use array_diff like this:
$params_needed = ["song_name", "artist_name", "song_release_date",
"song_genre", "song_medium"];
$given_params = array_keys($_POST);
$missing_params = array_diff($params_needed, $given_params);
if(!empty($missing_params)) {
// uh oh, someone didn't complete the form completely...
}
How I approach this is by using array_map() so I can return all the values in the array whilst checking if it isset()
PHP 5.6 >
$args = array_map(function($key) {
return isset($_POST[$key]) ? array($key => $_POST[$key]) : someErrorMethod($key);
}, ["song_name", "artist_name", "song_release_date", "song_genre", "song_medium"]);
PHP 7+
$args = array_map(function($key) {
return array($key => $_POST[$key] ?? someErrorMethod($key));
}, ["song_name", "artist_name", "song_release_date", "song_genre", "song_medium"]);
Your error method could look something like this:
function someErrorMethod($key) { die("$key cannot be empty."); }
Inside of your $args variable, you will have an array of key => value. For example,
echo $args['song_name'];

Set variable value to function result in PHP

This code:
function getId() {
$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri_segments = explode('/', $uri_path);
echo $uri_segments[3];
}
...extracts the url segment from a url. Say my url is "mysite.com/a/b/1234"
The code outputs 1234
I want to populate the below code wih 1234 using the function like this
$res = $api->query('bibs/getId();', array(
so its the same as
$res = $api->query('bibs/1234', array(
....but it doesn't work. Any ideas? Do I need to parse or something?
Thanks
The echo statement is described in the manual as:
echo — Output one or more strings
By "output", what is meant here is sending the string to the user - displaying it on the terminal of a command-line script, or sending it to the user's web browser.
What you are looking for is to use the value elsewhere in your code, which is known as "returning" the variable. There is a manual page about returning values.
The next thing you need to do is combine that value with the fixed string 'bibs/'. For that you can use either string concatenation or string interpolation.
In your function you need to actually return the value you want to use of it:
function getId() {
$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri_segments = explode('/', $uri_path);
return $uri_segments[3];
}
Then you could output the result,
echo getId();
or assign it to another variable
$id = getId();
or use it directly (by concatanating to the other string:
$res = $api->query('bibs/'.getId(), array(...
// the same when assigning it to a variable before:
$id = getId();
$res = $api->query('bibs/'.$id, array(...
Please see IMSoP's answer for very useful explanations and links!
You can try it like this:
$res = $api->query('bibs/' . getId(), array(

mysqli_real_escape_string with array in php? [duplicate]

This question already has an answer here:
Is is bad practice to use array_walk with mysqli_real_escape_string?
(1 answer)
Closed 1 year ago.
My code is like this
public function addQuestions($data){
$ans = array();
$ans[1] = $data['ans1'];
$ans[2] = $data['ans2'];
$ans[3] = $data['ans3'];
$ans[4] = $data['ans4'];
$ans= mysqli_real_escape_string($this->db->link, $data[$ans]);
}
Is this right way to use array in this sql function ??
Since you wish to do something to each element of array $ans, it would be most appropriate to use array_map(), as follows:
public function addQuestions($data){
$ans = array();
$ans[1] = $data['ans1'];
$ans[2] = $data['ans2'];
$ans[3] = $data['ans3'];
$ans[4] = $data['ans4'];
$escaped_ans = array_map(function( $e ) {
return mysqli_real_escape_string( $this->db->link, $e);
}, $ans );
I don't have enough reputation to comment on Milan's post, but beware of array_walk, it won't change your original array. For Milan's code to actually affect your array, the function would have to be
function myescape(&$val) //Note the '&' which calls $val by reference.
{
$val = mysqli_real_escape_string($val);
}
array_walk($ans, 'myescape');
To answer your question though:
public function addQuestions($data){
$ans = array('',$data['ans1'],$data['ans2'],$data['ans3'],$data['ans4']);
//I would recommend using an object/associative array in this case though, just the way $data is already
$ans_escaped = array_map(function($val) {
return mysqli_real_escape_string($this->db->link, $val);
}, $ans);
//do whatever you need to do with escaped array
}
My advice though, would be to really look into prepared statements. It might just seem like extra work that you don't want to bother with - at first - but once you learn it, you will never want to do it any other way.
Since you have an array, and you want mysqli_real_escape_string on each element of an array, you can use array_walk():
function myescape($val)
{
return mysqli_real_escape_string($val);
}
... then
array_walk($ans, 'myescape');
if you use MYSQL PDO you won't need add "mysqli_real_escape_string" because all your variables a safe (from SQL injection) after you bind it
http://php.net/manual/en/pdostatement.bindparam.php

passing indefinite number of arguments to function without using an array

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.

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

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

Categories