- php: how to get associative array key from numeric index?
- Php assoc array to index
- How to get Array index in foreach
- 2 Answers 2
- Targeting a multi dimensional associative array part by index
- 3 Answers 3
- PHP Associative Arrays
- Example
- Loop Through an Associative Array
- Example
- Complete PHP Array Reference
- PHP Exercises
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
php: how to get associative array key from numeric index?
You don’t. Your array doesn’t have a key [1] . You could:
- Make a new array, which contains the keys:
$newArray = array_keys($array); echo $newArray[0];
echo current(array_keys($array));
echo array_search('value', $array);
This all depends on what it is exactly you want to do. The fact is, [1] doesn’t correspond to «one» any which way you turn it.
$array = array( 'one' =>'value', 'two' => 'value2' ); $allKeys = array_keys($array); echo $allKeys[0];
If you only plan to work with one key in particular, you may accomplish this with a single line without having to store an array for all of the keys:
Or if you need it in a loop
foreach ($array as $key => $value) < echo $key . ':' . $value . "\n"; >//Result: //one:value //two:value2
I’m well aware of that. But given the fact that topicstarter is new to php, this could have been what he was trying to achieve and just didn’t know of the foreach syntax 😉
$array = array( 'one' =>'value', 'two' => 'value2' ); $keys = array_keys($array); echo $keys[0]; // one echo $keys[1]; // two
function asoccArrayValueWithNumKey(&$arr, $key) < if (!(count($arr) >$key)) return false; reset($array); $aux = -1; $found = false; while (($auxKey = key($array)) && !$found) < $aux++; $found = ($aux == $key); >if ($found) return $array[$auxKey]; else return false; > $val = asoccArrayValueWithNumKey($array, 0); $val = asoccArrayValueWithNumKey($array, 1); etc.
Haven’t tryed the code, but i’m pretty sure it will work.
If it is the first element, i.e. $array[0] , you can try:
If it is the second element, i.e. $array[1] , you can try:
I think this method is should be used when required element is the first, second or at most third element of the array. For other cases, loops should be used otherwise code readability decreases.
The key function helped me and is very simple:
The key() function simply returns the key of the array element that’s currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.
'apple', 'fruit2' => 'orange', 'fruit3' => 'grape', 'fruit4' => 'apple', 'fruit5' => 'apple'); // this cycle echoes all associative array // key where value equals "apple" while ($fruit_name = current($array)) < if ($fruit_name == 'apple') < echo key($array).'
'; > next($array); > ?>
The above example will output:
Please don’t just post a link; it might not work in the future. Instead, expand on what the function does and how to use it.
Get the most frequent occurrence(s) in an array:
$ php --version PHP 7.4.3 (cli) (built: Oct 6 2020 15:47:56) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0, Copyright (c) Zend Technologies with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies $ php -a Interactive mode enabled php > $a = array_count_values(array('abc','abc','def','def','def')); php > var_dump($a); array(2) < ["abc"]=>int(2) ["def"]=> int(3) > php > arsort($a); php > var_dump($a); array(2) < ["def"]=>int(3) ["abc"]=> int(2) > php > var_dump(array_key_first($a)); string(3) "def" php > var_dump(array_keys($a)[1]); string(3) "abc"
If you have the key, you can easily query the value (= the frequency).
Php assoc array to index
// Before php 5.4
$array = array(1,2,3);
// since php 5.4 , short syntax
$array = [1,2,3];
// I recommend using the short syntax if you have php version >= 5.4
Used to creating arrays like this in Perl?
Looks like we need the range() function in PHP:
$array = array_merge (array( ‘All’ ), range ( ‘A’ , ‘Z’ ));
?>
You don’t need to array_merge if it’s just one range:
There is another kind of array (php>= 5.3.0) produced by
$array = new SplFixedArray(5);
Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.
Supposing a large string-keyed array
$arr=[‘string1’=>$data1, ‘string2’=>$data2 etc. ]
when getting the keyed data with
php does *not* have to search through the array comparing each key string to the given key (‘string1’) one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it’s all hidden away.
However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :
Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It’s also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).
When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => 23 ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=0, is_ref=0)int 23
but :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => ’23’ ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=1, is_ref=0)string ’23’ (length=2)
or :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => [1,2], ‘too’ => [1,2] ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
‘too’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
This function makes (assoc.) array creation much easier:
function arr (. $array )< return $array ; >
?>
It allows for short syntax like:
$arr = arr ( x : 1 , y : 2 , z : 3 );
?>
Instead of:
$arr = [ «x» => 1 , «y» => 2 , «z» => 3 ];
// or
$arr2 = array( «x» => 1 , «y» => 2 , «z» => 3 );
?>
Sadly PHP 8.2 doesn’t support this named arguments in the «array» function/language construct.
How to get Array index in foreach
I have a foreach loop in php to iterate an associative array. Within the loop, instead of increamenting a variable I want to get numeric index of current element. Is it possible.
$arr = array('name'=>'My name','creditcard'=>'234343435355','ssn'=>1450); foreach($arr as $person) < // want index here >
$arr = array('name'=>'My name','creditcard'=>'234343435355','ssn'=>1450); $counter =0; foreach($arr as $person) < // do a stuff $counter++; >
2 Answers 2
Use this syntax to foreach to access the key (as $index ) and the value (as $person )
foreach ($arr as $index => $person)
Why would you need a numeric index inside associative array? Associative array maps arbitrary values to arbitrary values, like in your example, strings to strings and numbers:
$assoc = [ 'name'=>'My name', 'creditcard'=>'234343435355', 'ssn'=>1450 ];
Numeric arrays map consecutive numbers to arbitrary values. In your example if we remove all string keys, numbering will be like this:
$numb = [ 0=>'My name', 1=>'234343435355', 2=>1450 ];
In PHP you don’t have to specify keys in this case, it generates them itself. Now, to get keys in foreach statement, you use the following form, like @MichaelBerkowski already shown you:
foreach ($arr as $index => $value)
If you iterate over numbered array, $index will have number values. If you iterate over assoc array, it’ll have values of keys you specified.
Seriously, why I am even describing all that?! It’s common knowledge straight from the manual!
Now, if you have an associative array with some arbitrary keys and you must know numbered position of the values and you don’t care about keys, you can iterate over result of array_values on your array:
foreach (array_values($assoc) as $value) // etc
But if you do care about keys, you have to use additional counter, like you shown yourself:
$counter = 0; foreach ($assoc as $key => $value) < // do stuff with $key and $value ++$counter; >
Or some screwed functional-style stuff with array_reduce , doesn’t matter.
Targeting a multi dimensional associative array part by index
How can I target a multi-dimensional associative array by index? I need to be able to do something along the lines of this.
$x=2; $assoc_array = array( "red" => array(1,2,3,4,5), "green" => array(1,2,3,4,5), "blue" => array(1,2,3,4,5) ); array_push($assoc_array[$x],6);
3 Answers 3
You actually can do that. As an alternative, you can use $assoc_array[$x][] = 6
EDIT: The above is the answer for what you asked. The code below is for what I think you need, but didn’t state clearly:
$x = 2; $keys = array_keys($assoc_array); var_dump($assoc_array[$keys[$x]]);
+1 Was just posting the same. @pagewil: I have to note that if you have to do this your code has design problems.
Red being 0, green being 1, and blue being 2 or the $x=2 part.
If my answer is correct, be sure to check the checkbox to the left of this post so I can gain points. Points are what motivates me to continue to answer questions. Thank you for your time.
$x=2; $assoc_array = array( "red" => array(1,2,3,4,5), "green" => array(1,2,3,4,5), "blue" => array(1,2,3,4,5) ); $c = 0; foreach ($assoc_array as $key => $value) < if ($c == $x) < array_push($value, 6); $assoc_array[$key] = $value; >$c++; >
You must reference them via the key which in this case is the colour values you have given. To add a new element to the first item (red) you would use:
Using $assoc_array[$x][] = 6; will create a new array key with the identifier of $x unless $x is either red, green or blue.
The above method works but is massively convoluted if you just wish to reference an existing array value.
Part of the idea of giving a string value as an array key is to allow the easy reference of the array values via a related string rather than a meaningless number.
PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
The named keys can then be used in a script:
Example
$age = array(«Peter»=>»35», «Ben»=>»37», «Joe»=>»43»);
echo «Peter is » . $age[‘Peter’] . » years old.»;
?>?php
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use a foreach loop, like this:
Example
foreach($age as $x => $x_value) echo «Key=» . $x . «, Value=» . $x_value;
echo «
«;
>
?>
Complete PHP Array Reference
For a complete reference of all array functions, go to our complete PHP Array Reference.
The reference contains a brief description, and examples of use, for each function!
PHP Exercises
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.