0

How do you replace all non matches from one array that are not defined within the other array, i have kind of got working but its not exactly right. as i will show you.

the result is, but wrong.

- - £ 8 - - - - - - - -

The required result should be

 £ 8 - - 

this is how my code is

$vals_to_keep = array(8, 'y', '£');

$replace_if_not_found = array('£', 8, '#', 't'); // replace if not in above array

$result = '';

foreach ($replace_if_not_found as $d) {
 foreach ($vals_to_keep as $ok) {
    if(strcmp($d, $ok) == 0){
    $result .= $d . " ";
    }else 
    $result .= str_replace($d, $ok ,'-') . " ";
    }
}
echo $result;

2 Answers 2

1

use in_array http://php.net/manual/en/function.in-array.php

foreach ($replace_if_not_found as $d) {
if (in_array($d, $vals_to_keep)) 
    $result .= $d . " ";
else 
    $result .= str_replace($d, $ok ,'-') . " ";
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could loop over all of the items in $replace_if_not_found replacing them with -, or not, as appropriate.

Using closure in PHP 5.3 or above

$result = array_map(function($item) use ($vals_to_keep) {
    return in_array($item, $vals_to_keep, TRUE) ? $item : '-';
}, $replace_if_not_found);
echo implode(' ', $result);

Using a foreach loop

$result = array();
foreach ($replace_if_not_found as $item) {
    if (in_array($item, $vals_to_keep, TRUE)) {
        $result[] = $item;
    } else {
        $result[] = '-';
    }
}
echo implode(' ', $result;

2 Comments

what happened to array_pad array_intersect form your first answer, that was a very neat solution
it wouldn't work for arrays like array('£', 8, 'a', 'b', '£')

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.