2

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/>";
    }
}
0

4 Answers 4

3

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/>";
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

This one literally answers your question, but again... what are you trying to accomplish?
It's perfect, thanks. I can't mark it as correct yet. I'm using this code to replace names from database with other names (if it's in the array). Perfect.
One addition, how would I replace a single variable with it's array key? Like $var = "Name2"; $array = array("Name2" => "NameX"); str_replace($var, $array"), doesn't work, and the array will have multiple values
$var = $array[$var]; i guess. but be careful. that would just work if $array has the key "Name2"
1

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

Comments

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

Comments

0
    $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);

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.