1

I have an array $indexedarray

printr($indexedarray) gives something like this

array (size=3)
  0 => string 'Homes' (length=5)
  1 => string 'Apartments' (length=10)
  2 => string 'Villas' (length=6)

I want to change this arrays index also same as value, like

array (size=3)
  'Homes' => string 'Homes' (length=5)
  'Apartments' => string 'Apartments' (length=10)
  'Villas' => string 'Villas' (length=6)

is it posssible??

1

2 Answers 2

3

You can use array_combine:

$indexedarray= ['Homes', 'Apartments', 'Villas'];
print_r(array_combine($indexedarray, $indexedarray));

Gives:

Array
(
    [Homes] => Homes
    [Apartments] => Apartments
    [Villas] => Villas
)

But be aware that your duplicate values will be dropped. Keys will be unique!

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

7 Comments

What if those values are dynamic? How will know know what values to put into $arr?
At the hour of need, it can be done, but not before!
You mean at the time of building this array?
Yes, at the time of building that array
Yes it can be done when initializing - $indexedarray[$value] = $value instead of just $indexedarray[] = $value. But not sure how OP is filling this array!
|
-1

Try This :

$myArray = [
   0 => 'Homes',
   1 => 'Apartments',
   2 => 'Villas' ];


$newArray = [];

foreach($myArray as $key => $value){
  $newArray[$value] = $value;
}

var_dump($newArray);

1 Comment

It will remove duplicates as arrays can only have unique keys

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.