8

I am trying to convert indexed array to normal array. Basically what get is:

Array ( [0] => 14 [1] => 19 [2] => 20 )

And I need is:

Array(14,19,20);

I tried over Google but not information found. I think this kind of function isn't available in PHP, is there any? please let me know!

Thanks, Asif

Capripio
  • 474
  • 11
  • 21

1 Answers1

17

You're chasing shadows:
Both of the arrays you've shown are equal.

There is no such thing as an unindexed array in PHP.

But if you really want to be sure, use $newArray = array_values($array)

MightyPork
  • 18,270
  • 10
  • 79
  • 133
  • Hmm, I am trying to query with wordpress tax_query but it doesn't seems to work. So I checked on WordPress docs and found that simple array without indexed is used. – Capripio Jul 31 '13 at 20:19
  • All arrays that are not associative (strings as keys) have numeric indices. Your problem is likely to be somewhere else. – MightyPork Jul 31 '13 at 20:20
  • @Capripio All arrays have some sort of index. – StephenTG Jul 31 '13 at 20:20
  • @MightyPork Are sets a type of array? – StephenTG Jul 31 '13 at 20:22
  • @StephenTG Okay.. only a data structure. My bad. – MightyPork Jul 31 '13 at 20:22
  • hmm, Yup thanks for answer I have found, Some how taxonomy's terms doesn't save! I am rechecking it! – Capripio Jul 31 '13 at 20:26
  • I disagree with the rationale given by @MightyPork, especially since @Capripio mentioned WP. Let's say you have a comma-separated list which you explode into array `exploded`. Using `exploded` as an argument in a function won't work until you 'reset' the array with `array_values`. – adam rowe Jan 02 '17 at 17:55
  • @adamrowe can you give a concrete example of that? – MightyPork Jan 03 '17 at 18:53
  • @MightyPork: WP-specific example follows. In my case, I had a comma-separated list of values stored for later use with WP's `has_tag`. This function wants an array instead. I couldn't just explode the string because the function needs the array in 'simple' format, as in `array('val1','val2','val3')`. So in this case, only the `array_values` from an exploded comma-separated list can be given to `has_tag`. – adam rowe Jan 03 '17 at 19:05
  • @adamrowe I meant a real working example, I'm curious what your _real_ problem was. Cause both `var_dump(explode(',', 'aa,bb,cc'));` and `var_dump(['aa', 'bb', 'cc']);` give exactly identical output. – MightyPork Jan 04 '17 at 20:13
  • FYI three years late to the convo: Another example are API functions that want a simple "array of strings" and won't work if they receive a numerically indexed array. – CK MacLeod Feb 20 '21 at 17:06