0

Just need a little help here about arrays. Because I am trying to create a code that when you click it it will replace a certain array values.

In the base array suppose that we have this array:

Array(
   [0] => Array(
      [id] => 1,
      [name] => xyz
   ),
   [1] => Array(
      [id] => 4,
      [name] => fsa
   ),
)

And in my new array I have something like this

Array(
   [id] => 4,
   [name] => pop
)

I have a validation like this: In the base array I put this array in $base_array and in my new array I have $update_array

$get_updated_array_id = $update_array[id];

for($x = 0; $x <= sizeof($base_array); $x++){

    $target = $base_array[$x]['id'];

    if($get_updated_array_id == $target){

        //should be replace the array value ID '4'

    }

}

So the final result should be:

 Array(
       [0] => Array(
          [id] => 1,
          [name] => xyz
       ),
       [1] => Array(
          [id] => 4,
          [name] => pop
       ),
    )

Any idea how can I do that? Thanks

5
  • array_splice() Commented Nov 18, 2013 at 23:06
  • 1
    php.net/manual/en/ref.array.php Commented Nov 18, 2013 at 23:06
  • When you say "click" wouldn't you mean javascript?? Commented Nov 18, 2013 at 23:11
  • Hmm no.. It should be in PHP Commented Nov 18, 2013 at 23:11
  • 1
    You can use array_map Commented Nov 18, 2013 at 23:16

3 Answers 3

2
<?php
$array = array(
    array('id' => 2,'name' => 'T'),
    array('id' => 4,'name' => 'S')
);

$replace = array('id' => 4,'name' => 'New name');

foreach ($array as $key => &$value) {
    if($value['id'] == $replace['id'] ) {
        $value = $replace;
    }
}

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

1 Comment

Hello sir in the if statement the variable $value is it the base array?
1
$new_array = array(
   [id] => 4,
   [name] => pop
);


$get_updated_array_id = $update_array[id];

for($x = 0; $x <= sizeof($base_array); $x++){
    $target = $base_array[$x]['id'];
    if($get_updated_array_id == $target){
        $base_array[$x] = $new_array;
    }
}

Comments

1
//PHP >= 5.3

array_walk($base_array, function (& $target) use ($update_array) {
    if ($target['id'] == $update_array['id']) {
        $target = $update_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.