Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an array without keys in a loop

Tags:

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.

like image 588
jdp Avatar asked Apr 21 '11 22:04

jdp


People also ask

How do you iterate through an array?

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.

Can you use a for loop for an array?

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.

Can an array have keys?

No. Arrays can only have integers and strings as keys.

How do you declare an array in a for loop?

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.


2 Answers

you can't have an array without keys.

Array(19,18,21) 

this array has keys 0,1 and 2.

like image 156
Headshota Avatar answered Oct 19 '22 14:10

Headshota


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.

like image 42
KingCrunch Avatar answered Oct 19 '22 12:10

KingCrunch