0

i was wondering if there is a "String...stringArray" equivalent in PHP, something that can build an array based on "stringArray" parameters, i.e.

Java:

public void method1(){
    int aNumber = 4;
    String string1 = "first string";
    String string2 = "second string";
    String string3 = "third string";

    processStrings(aNumber, string1, string2, string3);
    /*
       string1, string2 and string3 will become b = {string1, string2, string3}
       in function "processStrings"
    */
}

public void processStrings(int a, String...b){
    System.out.println(b[0]); //in this case it will print out "first string"
    System.out.println(b[1]); //in this case it will print out "second string"
    System.out.println(b[2]); //in this case it will print out "third string"
}

Is there a way to do the same thing with PHP?

I know i can use

function processStrings($a, $b){}

and then call it like this

function method1(){
    $myInt = 4;
    $strings = array("first string","second string","third string");
    processStrings($myInt, $strings);
}

But i would like to know if there is a way to pass an undefined number of parameters like i do with Java

3
  • You have over a thousand reputation. I'm sure you can think of a better title for your question. Commented Mar 16, 2013 at 16:04
  • There is a question related to yours, did you see it? stackoverflow.com/questions/10128477/… Commented Mar 16, 2013 at 16:11
  • @GökhanÇoban No i didn't see it, however i need my function to require at least 2 parameters (possibly without having to manually check if func_num_args>=2)... Commented Mar 16, 2013 at 16:21

1 Answer 1

0

From php manual: func_get_args()

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs<br />\n";
    if ($numargs >= 2) {
        echo "Second argument is: " . func_get_arg(1) . "<br />\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
    }
}

foo(1, 2, 3);
?>

While you can do it, i offer not to define any arguments in your function, because it gets very confusing when any of the defined arguments are omitted.

Sign up to request clarification or add additional context in comments.

3 Comments

And what if it is required to have at least 2 parameters? i.e. function1($a,$b [,$c...]) How can i do it (possibly without having to manually check if func_num_args>=2)?
You can define arguments as i didn't offer in my answer. You should know that func_get_args() will give all of the arguments as array.
There is no exact equivalent in php like your usage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.