Change the value in the array key that has a specific value under the key in php

What's the shortest way to change multiple values ​​in an array key that has a specific value in it?

For example, I have this array:

array(2) {
  [0]=>
  array(5) {
    ["state"]=>
    string(6) "active"
    ["payer_mail"]=>
    string(12) "mail@none.com"
    ["start"]=>
    string(12) "06/05/2015"
    ["end"]=>
    string(8) "08/07/2017"
    ["price"]=>
    string(8) "45.00"
    ["keystring"]=>
    string(8) "493457025"
  }
  [1]=>
  array(6) {
    ["place"]=>
    string(2) "47"
    ["state"]=>
    string(8) "canceled"
    ["payer_mail"]=>
    string(12) "mail@none.com"
    ["start"]=>
    string(9) "20/8/2014"
    ["end"]=>
    string(10) "20/10/2017"
    ["price"]=>
    string(5) "95.00"
    ["keystring"]=>
    string(8) "34879205"
  }
}

      

And I want to change the value of a "state"

key with a value "34879205"

for its subcategory "keystring"

.

+3


source to share


3 answers


Another way I have found is:



$key = array_search('34879205', array_column($array, 'keystring'));
$array[$key]['state'] = 'newvalue';

      

+1


source


You can use foreach()

: -

foreach($array as &$value) {
    if ($value['keystring'] == '34879205'){
        $value['state'] = "";//change value here
    }
}

      



Output: - https://eval.in/838789

+2


source


You can use array_map function

$result = array_map(function ($element) {
    if ($element['keystring'] === '34879205') {
        $element['state'] = 'new_state';
    }

    return $element;
}, $array);

      

+1


source







All Articles