Reputation: 581
I have an array (myArray) which looks like
Array(
[0] => Computer
[1] => House
[2] => Phone
)
I'm trying to set each value dynamically to a number for example
$newValues = [
"computer" => 0,
"House" => 1,
"Phone" => 2,
];
I have the below loop
$y = 0;
for ($x = 0; $x < count($myArray); x++){
$values = [
$myArray[$x] = ($y+1)
];
y++;
}
This incorrectly produces
Array(
[0] => 3
)
Upvotes: 0
Views: 1052
Reputation: 35337
Like the others have said, array_flip will work, however, your actual problems in the code you've written are:
$myArray[$x] = ($y+1)
should be $myArray[$x] => ($y+1)
However this type of assignment really isn't necessary as the next problems will show:
To append to $values, you could use:
$values[$myArray[$x]] = $y+1;
Upvotes: 0
Reputation: 5690
use array_flip()
which — Exchanges all keys with their associated values in an array
<?php
$a1=array("0"=>"Computer","1"=>"House","2"=>"Phone");
$result=array_flip($a1);
print_r($result);
?>
then output is:
Array
(
[Computer] => 0
[House] => 1
[Phone] => 2
)
for more information
http://php.net/manual/en/function.array-flip.php
Upvotes: 1
Reputation: 372
If I good understand, you want to flip values with keys, so try to use array_flip()
.
If becomes to work with array first try to do some research in PHP Array functions. ;)
Upvotes: 1