ram shah
ram shah

Reputation: 81

How to pass input value as array instead of passing only one value where array_walk is used in PHP?

Here I created Hashmap array in PHP. I gave input as $keys = str_split('cat1hen') which give output 'doga@nt'.

$rule =
[
    "c" => "d",
    "a" => "o",
    "t" => "g",
    "h" => "a",
    "1" => "@",
    "e" => "n",
    "n" => "t"
];

$keys = str_split('cat1hen');

$output = [];
array_walk($keys,
function($item, $index) use($rule,$keys, &$output) {
    if($rule[$item] == '@' && isset($keys[$index + 1])) {
        $output[] = $rule[$keys[$index + 1]];
        return;
    }
    if(isset($keys[$index - 1]) && $rule[$keys[$index - 1]] == '@') {
        $output[] = '@';
        return;
    }
    $output[] = $rule[$item];
    return;
},
$keys);
echo implode($output);

Instead of giving one input value,I want to give input as array with many value i.e $keys = ['cat1hen','cathen','hencat'] which should give output as ['doga@nt','dogant','antdog'].How to modify code to do so??

Upvotes: 2

Views: 57

Answers (2)

u_mulder
u_mulder

Reputation: 54831

As another solution without regexps, you can wrap your array_walk into a function and map it to each element of array:

function myFunction($sourceString)
{
    $rule =
        [
            "c" => "d",
            "a" => "o",
            "t" => "g",
            "h" => "a",
            "1" => "@",
            "e" => "n",
            "n" => "t"
        ];

    $keys = str_split($sourceString);

    $output = [];
    array_walk($keys,
        function ($item, $index) use ($rule, $keys, &$output) {
            if ($rule[$item] == '@' && isset($keys[$index + 1])) {
                $output[] = $rule[$keys[$index + 1]];
                return;
            }
            if (isset($keys[$index - 1]) && $rule[$keys[$index - 1]] == '@') {
                $output[] = '@';
                return;
            }
            $output[] = $rule[$item];
            return;
        },
        $keys);
    return implode($output);
}

print_r(array_map('myFunction', ['cat1hen','cathen','hencat']));

Sample fiddle.

Upvotes: 0

Andreas
Andreas

Reputation: 23958

I just slightly modified my code I answered your previous question with.

Added a foreach to loop the words.

$rule = 
[
"c" => "d",
"a" => "o",
"t" => "g",
"h" => "a",
"1" => "@",
"e" => "n",
"n" => "t"
];
$orders = ['cat1hen','cathen','hencat'];

foreach($orders as $order){
    $arr = str_split($order);

    $str ="";
    foreach($arr as $key){
        $str .= $rule[$key];
    }

    $str = preg_replace("/(.*?)(@)(.)(.*)/", "$1$3$2$4", $str);
    echo $str . "\n";
}

//doga@nt
//dogant
//antdog

https://3v4l.org/LhXa3

Upvotes: 2

Related Questions