Wednesday, June 19, 2013

How to replace the value of certain key in array using PHP?

Today I needed to replace the value of certain key in array. I do not need to add another key and value. Rather, replace an existing key's value with another value.
Since I am using an associative array and knew the key's name as well. I wrote the following code and it worked.
PHP
$array = array('product' =>'iphone', 'price' =>'4500', 'model'=>'5G');

$array['price'] = '5700'; // say you wanted to change the value of key 'price'

print_r($array);

//outputs : array('product' =>'iphone', 'price' =>'5700', 'model'=>'5G');

If you could want to rebuild the array and keep the element's order, you can use following function.
<?php
function replace_key($find, $replace, $array) {
 $arr = array();
 foreach ($array as $key => $value) {
  if ($key == $find) {
   $arr[$replace] = $value;
  } else {
   $arr[$key] = $value;
  }
 }
 return $arr;
}

//example
$array = array('test' => 0, 'replace this' => 1, 3 => 'hey');
echo '<pre>', print_r($array, true), '</pre>';
$array = replace_key('replace this', 'with this', $array);
echo '<pre>', print_r($array, true), '</pre>';
?>

3 comments:

  1. I want to overwrite the value of post.
    Like I want to do something like this:
    $this->input->post('username') = 'User Name'; //Overwrite the value of index

    How will I do it?

    ReplyDelete
  2. If array is :
    $arr =
    (ram => name
    bca => class
    ram1 => name
    bca1 => class);

    output array should be

    name => ram,ram1
    class => bca,bca1
    how will i do this

    ReplyDelete
  3. this is first array
    $decutionvalue =
    Array
    (
    [ESIMemberContribution] => 169
    [EPFCompanyContribution] => 980
    [EPFMemberContribution] => 840
    )

    this is second array

    $deduction =
    Array
    (
    [id] => 80
    [Job_Type] => level x
    [Basic] => 7000
    [BusinessCommission] => 1058
    [TransportAllowance] => 1600
    [ESIMemberContribution] => 169
    [EPFCompanyContribution] => 14
    [EPFMemberContribution] => 12
    )



    using this code after that you can get




    foreach($decutionvalue as $key => $mainrow){

    foreach($deduction as $key1 => $mainrow1){

    if($key == $key1){


    $deduction[$key] = $mainrow;

    }



    }

    }


    OUTPUT :
    $deduction =
    Array
    (
    [id] => 80
    [Job_Type] => level x
    [Basic] => 7000
    [BusinessCommission] => 1058
    [TransportAllowance] => 1600
    [ESIMemberContribution] => 169
    [EPFCompanyContribution] => 980
    [EPFMemberContribution] => 840
    )

    ReplyDelete