How to increase php string by 1: 1. Create a new php sample file; 2. Create the "function inc($s) {...}" method; 3. Pass "while ($n-- > 0) {$s = inc($s);}" Calculate the string except the last character, and then carry.
The operating environment of this tutorial: Windows 10 system, PHP version 8.1, DELL G3 computer
How to increase the php string by 1 ?
php Numeric string 1 operation accumulates and adds one (no overflow)
* inc.php
<?php function inc($s) { if (empty($s)) {return "1";} if ( ! isset($s[1]) ) { $code = ord($s[0]) + 1; if ($code <= ord("9")) { return chr($code); } return "10"; } $n = strlen($s); $code = ord($s[$n-1]) +1; if ($code <= ord("9")) { return substr($s, 0, $n-1).chr($code); } return inc(substr($s, 0, $n-1))."0"; } $s = "2147483647"; $n = 10000; while ($n-- > 0) { // printf("%s\n", $s); $s = inc($s); } printf("%s\n", $s); // "2147493647"
Recursion, if carry is needed , first calculate the string excluding the last character, and set the last character to '0'; single numeric characters 0-9 are obviously easy to handle.
* test:
<?php $m = 2147483647; $n = 10000; while ($n-- > 0) { // printf("%d\n", $m); $m++; } printf("%d\n", $m);
The comparison results are consistent
* add2.php // Traverse 1-4 uppercase letters
<?php function add($s) { if (empty($s)) {return "A";} if ( ! isset($s[1]) ) { $code = ord($s[0]) + 1; if ($code <= ord("Z")) { return chr($code); } return "AA"; } $n = strlen($s); $code = ord($s[$n-1]) +1; if ($code <= ord("Z")) { return substr($s, 0, $n-1).chr($code); } return add(substr($s, 0, $n-1))."A"; } $s = ""; do { $s = add($s); printf("%s\n", $s); } while ($s != "ZZZZ");
Recommended learning: "PHP video tutorial"
The above is the detailed content of How to increase php string by 1. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Mac version
God-level code editing software (SublimeText3)
