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' )
TylerH
  • 20,799
  • 66
  • 75
  • 101
Akash
  • 4,956
  • 11
  • 42
  • 70

4 Answers4

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.

jeroen
  • 91,079
  • 21
  • 114
  • 132
3
foreach ($arr as $k => $v) {
    if (is_int($k)) {
        unset($arr[$k]);
        $arr[$v] = 'U.S.';
    }
 }
Tim S
  • 5,023
  • 1
  • 34
  • 34
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.

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
-1

I would work with something like this:

foreach ( $array AS $key => $value )
{
 if ( is_numeric($key) )
 {
  $key = 'U.S';
 }
 $array[$key] = $value;
}
christopher
  • 615
  • 5
  • 11
  • Won't solve the problem. Have a look at what exactly he wants to pass as a argument. – clentfort Sep 26 '12 at 15:28
  • I see. The KEY is not the single variable added. it is the value – christopher Sep 26 '12 at 15:31
  • 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 – clentfort Sep 26 '12 at 15:34