Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an associative array by integer index in PHP

Tags:

php

I want to set the value of an associative array using the array index of the key/value pair. For example:

$my_arr = array( "bling" => "some bling", "bling2" => "lots O bling" ); $my_arr[1] = "not so much bling";  // Would change the value with key bling2. 

How can this be accomplish this without using the key string?

like image 419
Marty Avatar asked Jan 22 '11 16:01

Marty


People also ask

How can we access a specific value in an associative array in PHP?

You can use the PHP array_values() function to get all the values of an associative array.

Are PHP arrays associative or integer indexed?

PHP arrays can contain int and string keys at the same time as PHP does not distinguish between indexed and associative arrays.

What do associative arrays use for indexes?

Associative arrays differ from normal, fixed-size arrays in that they have no predefined limit on the number of elements, the elements can be indexed by any tuple as opposed to just using integers as keys, and the elements are not stored in preallocated consecutive storage locations.

How do you get the index of an element in an array in PHP?

We can get the array index by using the array_search() function. This function is used to search for the given element.


1 Answers

Use array_keys.

$keys = array_keys($my_arr); $my_arr[$keys[1]] = "not so much bling";  
like image 157
Donovan Avatar answered Oct 10 '22 07:10

Donovan