jdp
jdp

Reputation: 3516

Creating an array without keys in a loop

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.

Upvotes: 24

Views: 71581

Answers (5)

$array = array_values($array);

Upvotes: 1

ogunrinade gbolahan
ogunrinade gbolahan

Reputation: 21

You could try Array_column(the name of the array, then the positions you want to get). Then print_r (result)

Upvotes: 0

hounded
hounded

Reputation: 726

The closest you are going to get is to combine so your keys are your values

array_combine($array1,$array1) 

Upvotes: 1

KingCrunch
KingCrunch

Reputation: 131881

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.

Upvotes: 11

Headshota
Headshota

Reputation: 21449

you can't have an array without keys.

Array(19,18,21)

this array has keys 0,1 and 2.

Upvotes: 22

Related Questions