# php - Replace digits in a number with other random digits

547

Problem:

• I'm trying to write a function which replace four digits in a number
• Number syntax is XX.XXXXXXX (but length may vary but min. 8 digits)
• Digits I want to change always 5th, 6th, 7th and 8th (marked as Z --> XX.XXZZZZXXXX)
• The number to replace Z, must be random (or 4 random digits in each Z)

Example:

`x=12.3456789 --> function --> 12.34xxxx9`

Where xxxx is a random number with 4 digits or four different digits.

Documentation:

What I've tried:

Note: I'm starting with coding... super rookie here.

``````function mynumber(\$x) {
//ok, it's not elegant but here i'm trying to get a number of 4 digits instead of digit by digit
\$replacement = var_dump(random_int(1111, 9999));
//I've read about string replace but as the lenght may vary, i don't know how to delimitate the digits i want to change
\$x = str_replace(\$x, \$replacement, -?);
}
``````
821

#### Solution:

Use`substr_replace()` as`str_replace()` will replace other matching digits not just in the 5th through 8th place:

``````\$x = substr_replace(\$x, \$replacement, 5, 4);
``````

Also, you need to`return \$x;` in the function. Or to modify the passed variable, you need to pass it by reference:

``````function mynumber(&\$x) {
``````

People are also looking for solutions to the problem: php - What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such

Source