1

I have a function that accepts an array parameter as

array('employee_name' => 'employee_location' )

eg:
array('John' => 'U.S', 'Dave' => 'Australia', 'Unitech' => 'U.S' )

I wish to keep 'U.S' as the default location and a optional value, so

So If I pass

array('John', 'Dave' => 'Australia', 'Unitech')

Is there a in-build function in PHP that automatically converts it to

array('John' => 'U.S', 'Dave' => 'Australia', 'Unitech' => 'U.S' )
1
  • As you've written it, it's the array's values that need to be set, not the keys. Commented Sep 26, 2012 at 15:26

4 Answers 4

4

There is no built-in function for that.

You should loop through your array and check if the key is numeric. If it is, use the value as the key and add your default as the value.

Simple example (using a new array for clarity):

$result = array();
foreach ($arr as $key => $value)
{
  if (is_int($key))    // changed is_numeric to is_int as that is more correct
  {
    $result[$value] = $default_value;
  }
  else
  {
    $result[$key] = $value;
  }
}

Obviously this would break on duplicate names.

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

Comments

3

Note that MI6 will hunt you down: $agents = array('007' => 'UK'); will be transformed into $agents['UK'] => 'US'... I know UK and US have a "special relation", but this is taking things a tad far, IMHO.

$agents = array('007' => 'UK');
$result = array();
foreach($agents as $k => $v)
{
    if (is_numeric($k))//leave this out, of course
    {
        echo $k.' won\'t like this';//echoes 007 won't like this
    }//replace is_numeric with is_int or gettype($k) === 'integer'
    if (is_int($k))
    {//'007' isn't an int, so this won't happen
        $result[$v] = $default;
        continue;
    }
    $result[$k] = $v;
}

Result and input look exactly alike in this example.

Comments

3
foreach ($arr as $k => $v) {
    if (is_int($k)) {
        unset($arr[$k]);
        $arr[$v] = 'U.S.';
    }
 }

1 Comment

+1 Though you should use is_int() instead of is_numeric(); see other answer.
-1

I would work with something like this:

foreach ( $array AS $key => $value )
{
 if ( is_numeric($key) )
 {
  $key = 'U.S';
 }
 $array[$key] = $value;
}

3 Comments

Won't solve the problem. Have a look at what exactly he wants to pass as a argument.
I see. The KEY is not the single variable added. it is the value
At the time I wrote the comment it did not work, a value would have always be present, some values will have numeric and others will have strings as values. With your latest edit you just copied the solution of @jeroen

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.