7

I have an array, f. e.:

$arr = array(
    4 => 'some value 1',
    7 => 'some value 2',
    9 => 'some value 3',
    12 => 'some value 4',
    13 => 'some value 5',
    27 => 'some value 6',
    41 => 'some value 7'
)

I need to create another array, where values will be array, but the keys will be the same; like this:

$arr = array(
    4 => array(),
    7 => array(),
    9 => array(),
    12 => array(),
    13 => array(),
    27 => array(),
    41 => array()
)

Is there some build-in function in PHP for do that? array_keys() didn't help me:

var_dump(array_keys($arr));

Returned:

array(7) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
  [5]=>
  int(5)
  [6]=>
  int(6)
}
3
  • array_keys() didn't help me. <- Show your code and where you are stuck Commented Jun 11, 2015 at 12:28
  • 1
    By the way, my solusion works faster than this, i think,because less function calls :) eval.in/379770 Commented Jun 11, 2015 at 13:01
  • Yes, it is possible. Commented Jun 11, 2015 at 13:28

4 Answers 4

11

Try this . You can use array_fill_keys() for more info follow this link

$arr = array(
    4 => 'some value 1',
    7 => 'some value 2',
    9 => 'some value 3',
    12 => 'some value 4',
    13 => 'some value 5',
    27 => 'some value 6',
    41 => 'some value 7'
);
$keys=array_keys($arr);

$filledArray=array_fill_keys($keys,array());
print_r($filledArray);
Sign up to request clarification or add additional context in comments.

Comments

3

This should work for you:

Just array_combine() your array_keys() from the old array, with an array_fill()'ed array full of empty arrays.

<?php

    $newArray = array_combine(array_keys($arr), array_fill(0, count($arr), []));
    print_r($newArray);

?>

output:

Array
(
    [4] => Array ()  
    [7] => Array ()    
    [9] => Array ()    
    [12] => Array ()    
    [13] => Array ()    
    [27] => Array ()
    [41] => Array ()

)

2 Comments

Its enough to use this array_fill_keys(array_keys($arr), array());, but yes, this is also another and longer solution...
and this is slower 40% :))))
1

Change values to array saving keys:

$arr2 = array_map(function ($i){
    return array();
}, $arr);

result

Array
(
    [4] => Array ( )  
    [7] => Array ( )    
    [9] => Array ( )    
    [12] => Array ( )    
    [13] => Array ( )    
    [27] => Array ( )
    [41] => Array ( )

)

1 Comment

Thanks. Its enough to use this array_fill_keys(array_keys($arr), array());, but yes, this is also another solution...
0

Try this:

foreach($arr as $key => $value) {
  $array[$key] = array('a','b','c');
}

1 Comment

Please never post code-only / "try this" answers on Stack Overflow.

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.