3

I have a PHP array like

$arr = array("c_m_email" => "[email protected]");

and I can access the email by

$arr['c_m_email'] 

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

5
  • No, an array value has one key and that is the only key you can use. Commented Jun 28, 2017 at 12:34
  • 1
    No, because the index is 'c_m_email' and not 0 Commented Jun 28, 2017 at 12:34
  • Possible duplicate of php: how to get associative array key from numeric index? Commented Jun 28, 2017 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]. Commented Jun 28, 2017 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. Commented Jun 28, 2017 at 13:05

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

reset($h);
echo current($h)

Comments

-1
    $i=0;
    $data=array();

   foreach($arr as $value){

       $data[$i] = $value;

       $i++;

    }

    print_r($data);

2 Comments

This is exactly what the PHP function array_values() does. So, why would you write the code for that by yourself?
Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.