Reputation: 65
I have an array in this form
([0] => 'string1' [1] => 'string2' [2] => 'string3' )
and a variable $lenght that I got from strlen(). Now I need to create an array in this form
('string1' => $lenght 'string2' => $lenght 'string3' => $lenght )
Any idea on how to do it? Thank you
Upvotes: 0
Views: 25
Reputation: 8600
Here is my solution
$a = array('Hello', 'World', 'PHP');
$a = array_flip($a);
array_walk($a, function(&$val, $key) {
$val = strlen($key);
});
var_dump($a);
Here is the result of this code: http://3v4l.org/HfUKN
You may also replace the array_walk call with a for
loop using a reference for the value.
Upvotes: 0
Reputation: 12039
Simply use a foreach()
. Example:
$arr = array('string1','string2','string3');
$length = "Your Val";
$newArr = array();
foreach($arr as $val){
$newArr[$val] = $length;
}
print '<pre>';
print_r($newArr);
print '</pre>';
Upvotes: 1