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
)
You can use array_flip($arr). link
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 . ;)
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
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.