简体   繁体   中英

php for loop assign variables in array

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

http://php.net/manual/en/function.array-flip.php

Like the others have said, array_flip will work, however, your actual problems in the code you've written are:

  1. You are using the wrong assignment operator for array keys:

$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:

  1. You are overwriting $values each iteration with a new array.

To append to $values, you could use:

$values[$myArray[$x]] = $y+1;
  1. If you really want 0 as your first value, don't use y+1 in your assignment.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM