user3056158
user3056158

Reputation: 719

How to replce ony array value with other array value in a specific index?

I have an array

$a=array([0]=>x [3]=>y);

$b=array([0]=>s [1]=>k  [2]=>m [3]=>z);

i want to replace array a's key value s with x and z with Y output of array will be

array([0]=>x [1]=>k  [2]=>m [3]=>y)

Upvotes: 1

Views: 64

Answers (5)

Adil Abbasi
Adil Abbasi

Reputation: 3291

<?php
   $a=array(0=>'x', 3=>'y');
   $b=array(0=>'s', 1=>'k',  2=>'m', 3=>'z');
   $result = $a+$b;
   ksort($result);
   print_r($result);
?>

OutPut:

Array ( [0] => x [1] => k [2] => m [3] => y )

Upvotes: 0

gwillie
gwillie

Reputation: 1899

Why not use union operator

$a = array(0=>'x', 3=>'y');
$b = array(0=>'s', 1=>'k',  2=>'m', 3=>'z');

// union of array $a and $b
$c = $a + $b;
// sort array by key, so output keys are sorted
ksort($c);
echo '<pre>' . print_r($c, true) . '</pre>';

OUTPUT

Array
(
    [0] => x
    [1] => k
    [2] => m
    [3] => y
)

Upvotes: 0

user2680766
user2680766

Reputation:

You may use array_replace as the other users have suggested.

OR

<?php
$a=array(0=>'x',3=>'y');
$b=array(0=>'s',1=>'k',2=>'m',3=>'z');
$c=$a+$b;
ksort($c);
print_r($c);
?>

Upvotes: 2

Prateek
Prateek

Reputation: 6965

Use array_replace - Replaces elements from passed arrays into the first array

<?php
  $a=array(0=>'P',3=>'R');
  $b=array(0=>'s',1=>'k',2=>'m',3=>'z');
  print_r(array_replace($a1,$a2));
?> 

Upvotes: 0

Make use of array_replace()

<?php
$a=array(0=>'x',3=>'y');
$b=array(0=>'s',1=>'k',2=>'m',3=>'z');
print_r(array_replace($b,$a));

OUTPUT :

Array
(
    [0] => x
    [1] => k
    [2] => m
    [3] => y
)

Upvotes: 0

Related Questions