mercredi 6 février 2019

How can I replace every second digit to another digit using if else statement in php?

I have a number that a user will put into a form - 12 digits. Every second digit needs to be replaced - if the digit is: 1 then make it 5 2 then make it 1 3 then make it 6 4 then make it 2 5 then make it 7 6 then make it 3 7 then make it 8 8 then make it 4 0 and 9 stay the same.

So for example: 343608111218 will end up being 383307121417.

Here is an example of what I'm currently doing, but I think it is long winded. This is just for the first number, so I'm assuming I could do something else?

$_POST['number'] = '343608111218';
preg_match_all('~(\d)~', $_POST['number'], $pregs);

if($pregs[1][1] === "1") {
$one = 5;
} 
elseif ($pregs[1][1] === "2"){
$one = 1;
}
elseif ($pregs[1][1] === "3"){
$one = 6;
}
elseif ($pregs[1][1] === "4"){
$one = 2;
}
elseif ($pregs[1][1] === "5"){
$one = 7;
}
elseif ($pregs[1][1] === "6"){
$one = 3;
}
elseif ($pregs[1][1] === "7"){
$one = 8;
}
elseif ($pregs[1][1] === "8"){
$one = 4;
}
$rep1 = (array_replace($pregs[1],array(1=>$one)));

If there is a way that I can reduce the amount of code, I would be very grateful. Thank you.

Aucun commentaire:

Enregistrer un commentaire