William N
William N

Reputation: 430

PHP, replacing array variable with other array variables

Here's sample code:

$array1 = array("Name1", "Name2", "Name3");
$array2 = array("Name2" => "NameX");
foreach($array1 as $val) 
{
    echo $val."<br/>";
}

This would output: Name1 Name2 Name3

How can I output this instead: Name1 NameX Name3

Yogesh Suthar submitted the correct reply:

 $array1 = array("Name1", "Name2", "Name3");

$array2 = array("Name2" => "NameX");
foreach($array1 as $val) {
    if (array_key_exists($val, $array2)) {
            echo $array2[$val];
    }
    else {
            echo $val."<br/>";
    }
}

Upvotes: 2

Views: 270

Answers (4)

Giacomo1968
Giacomo1968

Reputation: 26066

Will take your question literally & use the code you have.

$array1 = array("Name1", "Name2", "Name3");
$array2 = array("Name2" => "NameX");
foreach($array1 as $val) {
    if (array_key_exists($val, $array2)) {
            echo $array2[$val]."<br/>";
    }
    else {
            echo $val."<br/>";
    }
}

Upvotes: 3

Jason Small
Jason Small

Reputation: 1054

    $array1 = array("Name1", "Name2", "Name3");
enter code here$array2 = array("Name2" => "NameX");

//Loop tthrough replacement array 
foreach($array2 as $key => $word){
    //Loop through all the replacements
    foreach($array1 as $array1key => $item){

        if($item == $key){
        //if match found replace
        $array1[$array1key] = $word;

        }
    }   
}

print_r($array1);

Upvotes: 0

scones
scones

Reputation: 3345

foreach ($a1 as $v) {
  if (isset($a2[v]) && !empty($a2[$v]))
    echo "{$a2[$val]}<br />";
  else
    echo "$val<br />";
}

Upvotes: 1

keeg
keeg

Reputation: 3978

I think you are looking for array_replace()

<?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");

$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
?>

it will output:

Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

PHP: array_replace

Upvotes: 1

Related Questions