1

I need to change array value based on specific value. Take a look at this array below :

Array
( 
    [0] => Array
        (
            [id] => 5
            [title] => 
            [nomor] => 1
        )

    [1] => Array
        (
            [id] => 6
            [title] => 
            [nomor] => 2
        )

)

I need to change the array key based on nomor value. How can I do that?

1
  • 1
    change array key by it's own value? It's look like you want to change key with there own value. better to add your expected output. Commented Jul 27, 2019 at 18:28

2 Answers 2

4

You can use array_column for that (doc) as:

$arr = array_column($arr, null, "nomor");

Live example

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

Comments

0

The easiest way is to simply create a new array, loop through your existing one, and save each elements into the new one with the proper key.

foreach($array as $element) {
    $formatted_array[$element['nomor']] = $element;
}

Here is a working fiddle: https://3v4l.org/PlbJ1

Edit: Keep in mind though, if multiple elements have the same value as "nomor", the latest will override the previous one.

Edit 2: Per the other answer, PHP's array_column function seems to do this simpler.

2 Comments

This answer will work - but this can done with PHP build-in function which I think better practice
Yes, your solution is better, I updated. I wasn't aware of array_column. PHP seems to have lots of obscure array functions that I haven't actually seen in action before.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.