1

I have an array with string value in PHP for example : arr['apple'], arr['banana'], and many more -about 20-30 data (get it from some process). Now I want to get its value and return it to one variable.

For example, I have Original array is like this:

$arr['Apple']
$arr['Banana']
and more..

and result that I want is like this:

$arr[0] = "Apple"
$arr[1] = "Banana"
and more..

Any idea how to do that?

4 Answers 4

3

Why not using array_keys()?

$new_array = array_keys($array);
Sign up to request clarification or add additional context in comments.

Comments

1

Use array_flip()

$new_arr = array_flip($old_arr);

Demonstration

8 Comments

definitely, the simplest way around :)
This way, all the extra values in the array would be removed (since array keys must be unique).
@AmalMurali, Let's worry about that later... I hope he said more... Maybe it is Pineapple , Guava , Papaya.. yeah a lot more fruits are there right ? ;)
@CrossVander: The result will be an array. You can't echo/print it. Use print_r($new_arr); to inspect the contents of the array. Or use implode() if you want to join them into a comma-separated string: echo implode(', ', $new_arr);.
Hello, I want to ask what is "=>1" for? because my code is now like this: eval.in/142463 And I still can't call the variable $new[0], its output is: "Undefined offset: 0 in"
|
0

use foreach loop

foreach($arr as $key => $val){
    $new_var[] = $key; 
}

Comments

0

use array_keys function:

$keys = array_keys($arr);

It returns an array of all the keys in array.

Comments

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.