0

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
 )
4
  • could be there repeated values? Commented Aug 28, 2017 at 14:02
  • No, repeated values have been filtered out already Commented Aug 28, 2017 at 14:04
  • you are just ressetting values every time. $value= Commented Aug 28, 2017 at 14:08
  • $values [$myArray[$x]]= ($y+1); y++; Commented Aug 28, 2017 at 14:09

4 Answers 4

2

You can use array_flip($arr). link

Sign up to request clarification or add additional context in comments.

Comments

1

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. ;)

Comments

1

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

1 Comment

How can this be made dynamically, the values of the array will be changing constantly
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.