Skip to content

Language Shootout

A user-supported site Fastest, Shortest, Simplest

Reverse Complement

PHP #1 — Reverse Complement

Read DNA sequences and write out the reverse complement of each.

Time 1,094.0 ms
CPU time 993.6 ms
Peak memory 394,136 KB
gz 310 bytes — comments removed, gzipped
Style ★★★★☆
Implementation PHP — PHP (Zend) 8.5.9
By sysop-
Submitted September 24, 2026

Style assessment

Lean, idiomatic PHP that leans on the string stdlib exactly as a PHP practitioner would: strtr with paired translation strings for base complementing, strrev, and wordwrap(...,60,"\n",true) for the 60-column output instead of hand-rolled chunking. Naming is conventional (uppercase constants, snake_case function). What keeps it from 5s: the global $seq with the dubious 'no time-consuming argument passing' comment, the redundant exit; before the hoisted function, the closing ?> tag, and a feof-driven read loop where while(($line=fgets(STDIN))!==false) is the community-standard pattern; passing $seq as a parameter and using that loop would raise idiom and structure.

<?php
#
# The Computer Language Benchmarks Game
# http://benchmarksgame.alioth.debian.org/
#
# reverse complement in PHP
# contributed by Danny Sauer
#

# We'll need some definitions
define( 'LINE_LENGTH', 60 );
define( 'SRC', 'CGATMKRYVBHD');
define( 'DST', 'GCTAKMYRBVDH');
$str = '';
$seq = '';

# read in the file, a line at a time
while( !feof(STDIN) ) {
    $str = trim(fgets(STDIN));
    if( $str[0] == '>' ){
        # if we're on a comment line, print the previous seq and move on
        print_seq();
        echo $str, "\n";
    }else{
        # otherwise, just append to the sequence
        $seq .= $str;
    }
}
print_seq();

exit;

# print the sequence out, if it exists
function print_seq(){
    global $seq; # no time-consuming argument passing for us! :)
    if($seq != ''){
        echo wordwrap( strrev( strtr(strtoupper($seq), SRC, DST) ),
                       LINE_LENGTH, "\n", true ), "\n";
    }
    $seq = '';
}
?>

Back to Reverse Complement