Asked  7 Months ago    Answers:  5   Viewed   36 times

Given any character from a to z, what is the most efficient way to get the next letter in the alphabet using PHP?

 Answers

44

The most efficient way of doing this in my opinion is to just increment the string variable.

$str = 'a';
echo ++$str; // prints 'b'

$str = 'z';
echo ++$str; // prints 'aa' 

As seen incrementing 'z' give 'aa' if you don't want this but instead want to reset to get an 'a' you can simply check the length of the resulting string and if its >1 reset it.

$ch = 'a';
$next_ch = ++$ch; 
if (strlen($next_ch) > 1) { // if you go beyond z or Z reset to a or A
 $next_ch = $next_ch[0];
}
Wednesday, March 31, 2021
 
Gregosaurus
answered 7 Months ago
99
$chars = range('a', 'z');
$shift = 5;
$shifted = array_merge(array_slice($chars, $shift), array_slice($chars, 0, $shift));
$alphabet = array_combine($chars, $shifted);

Since there are 26 characters in your alphabet you can only shift them by 26 characters, meaning there are 26 possible combinations.

Wednesday, March 31, 2021
 
tika
answered 7 Months ago
11

See the manual for the increment operator:

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

Friday, May 28, 2021
 
inVader
answered 5 Months ago
96

The most efficient way would be using a pipeline.

Assuming you want everything for a given key and know all the keys already:

import redis

r = redis.Redis(host='localhost', port=6379, db=0)
p = r.pipeline()
for key in keys:
    p.hgetall(key)

for h in p.execute():
    print h

More information about pipelines can be found here: http://redis.io/topics/pipelining

Thursday, August 12, 2021
 
Michal Charemza
answered 3 Months ago
49
function Last7Days () {
    var result = [];
    for (var i=0; i<7; i++) {
        var d = new Date();
        d.setDate(d.getDate() - i);
        result.push( formatDate(d) )
    }

    return(result.join(','));
}

FIDDLE

Or another solution for the whole thing

function Last7Days () {
    return '0123456'.split('').map(function(n) {
        var d = new Date();
        d.setDate(d.getDate() - n);

        return (function(day, month, year) {
            return [day<10 ? '0'+day : day, month<10 ? '0'+month : month, year].join('/');
        })(d.getDate(), d.getMonth(), d.getFullYear());
    }).join(',');
 }

FIDDLE

Sunday, October 10, 2021
 
ranhan
answered 2 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :