1

Can I create a PHP function which will accept either integer or array values? Can the logic be determined upon reaching the function, or should it be done prior to calling it? (i.e. I want to avoid using one function for arrays, and another for single integers.)

I could have two arguments one integer, one array, and then call the function with one as null. But is a scenario where I don't know the type at the moment it would be called.

function my_function($integer, array $array)
{
    $integer = '';

    ...

Perhaps, before calling my function, I should convert my integer into a single keyed array so it wouldn't matter.

2 Answers 2

2

If you are certain you will only be passing an array or integer type, you could do the following:

function my_function($param)
{
    if (is_array($param)) {
      //treat param as array
    } else {
      //treat param as integer
    }
...
}
Sign up to request clarification or add additional context in comments.

Comments

0

PHP does not use strict datatyping. You can always check what type of "object" the argument is:

function my_function($value) {
    if ( is_array($value) ) {
        // it is an array
    } else if ( is_int($value) ) {
        // it is an integer
    } else {
        throw new InvalidArgumentException(__FUNCTION__.' expecting array or integer, got '.gettype($value));
    }
}

PHP has a bunch of type check global functions:

  • is_​array
  • is_​bool
  • is_​callable
  • is_​double
  • is_​float
  • is_​int
  • is_​integer
  • is_​long
  • is_​null
  • is_​numeric
  • is_​object
  • is_​real
  • is_​resource
  • is_​scalar
  • is_​string

1 Comment

The InvalidArgumentException exception would make sense here.

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.