This might be a brain fart, since it's a late day, but I'm stuck here.
I need to take a $_POST value from a select box. (It's an array), and convert it to a simple array that doesn't have any keys.
Here's the print_r from the item:
Array ( [0] => 19 [1] => 18 [2] => 21 )
Problem is, I need an array that looks like this:
Array(19,18,21)
Whenever I try to foreach() through the form field, I have to do something like this:
$row[] = $val;
But that leaves me with a numerical index.
What am I missing?
Thanks.
Iterating over an array You can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.
We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.
No. Arrays can only have integers and strings as keys.
You can declare (define) an array inside a loop, but you won't be able to use it anywhere outside the loop. You could also declare the array outside the loop and create it (eg. by calling new ...) inside the loop, in which case you would be able to use it anywhere as far as the scope the declaration is in goes.
you can't have an array without keys.
Array(19,18,21)
this array has keys 0,1 and 2.
Arrays (in PHP) always have (at least) numeric indices. However, you can extract the values via array_values(). This returns only the values of the given array. It of course has indices, but they are continous and they are numeric. Thats the most simple array representation you can have in PHP.
Update, just to make that clear: You cannot have an array without indices in PHP (as far as I know in any other language thats quite the same), because internaly arrays are always hashmaps and hashmaps always needs a key. The "most common key" are indices. You cannot omit the "keys". On the other side I dont the any reason why one should want it. If you dont want to use the keys, just dont use the keys and thats really all. PHP is quite gentle in this point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With