jumpman8947
jumpman8947

Reputation: 581

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
 )

Upvotes: 0

Views: 1052

Answers (4)

Devon Bessemer
Devon Bessemer

Reputation: 35337

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.

Upvotes: 0

Shafiqul Islam
Shafiqul Islam

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

Sebastian Tkaczyk
Sebastian Tkaczyk

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

Avihay m
Avihay m

Reputation: 551

You can use array_flip($arr). link

Upvotes: 2

Related Questions