3

I have a PHP array like

$arr = array("c_m_email" => "a@b.z");

and I can access the email by

$arr['c_m_email'] 

But is there another way to just write $arr[0]?

Marten
  • 1,376
  • 5
  • 28
  • 49
JenuRudan
  • 545
  • 1
  • 14
  • 30
  • No, an array value has one key and that is the only key you can use. – jeroen Jun 28 '17 at 12:34
  • 1
    No, because the index is `'c_m_email'` and not `0` – RiggsFolly Jun 28 '17 at 12:34
  • Possible duplicate of [php: how to get associative array key from numeric index?](https://stackoverflow.com/questions/4095796/php-how-to-get-associative-array-key-from-numeric-index) – Lars Beck Jun 28 '17 at 12:36
  • If you want to use [0] than you have to edit that array and set index from [c_m_email] to [0]. Otherwise you have to use [c_m_email]. – Ankesh Vaishnav Jun 28 '17 at 12:58
  • All those comments aren't true! Use ```array_values()``` as modsfabio said in the answer below and you can access the elements by their index. – Marten Jun 28 '17 at 13:05

3 Answers3

6

Use array_values()

array_values() returns all the values from the array and indexes the array numerically.

Manual: http://php.net/manual/en/function.array-values.php

modsfabio
  • 1,097
  • 1
  • 13
  • 29
0

If you want the first entry in the array, you could also do this:

reset($h);
echo current($h)
ErikL
  • 2,031
  • 6
  • 34
  • 57
-1
    $i=0;
    $data=array();

   foreach($arr as $value){

       $data[$i] = $value;

       $i++;

    }

    print_r($data);
harsh kumar
  • 165
  • 7
  • 1
    This is exactly what the PHP function `array_values()` does. So, why would you write the code for that by yourself? – Marten Jun 28 '17 at 14:49
  • Thank you for this code snippet, which may provide some immediate help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its educational value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Jun 28 '17 at 15:52