Skip to content

Instantly share code, notes, and snippets.

@mgng
Created February 4, 2014 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgng/8798175 to your computer and use it in GitHub Desktop.
Save mgng/8798175 to your computer and use it in GitHub Desktop.
array -> base64_encode
<?php
/**
* @param array $a
* @return string
*/
function array_to_base64_encode( array $a ) {
$table = preg_split('//', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', -1, PREG_SPLIT_NO_EMPTY);
$l = count($a);
$m = $l % 3;
$buf = array();
for( $i=0; $i<=$l-3; $i+=3 ) {
$j = ($a[$i] << 16) | ($a[$i+1] << 8) | $a[$i+2];
array_push( $buf, $table[$j >> 18 & 63], $table[$j >> 12 & 63], $table[$j >> 6 & 63], $table[$j & 63] );
}
if ( $m === 1) {
$j = $a[$i] << 16;
array_push( $buf, $table[$j >> 18 & 63], $table[$j >> 12 & 63], '==' );
} else if( $m === 2 ) {
$j = ( $a[$i] << 16) | ($a[$i + 1] << 8);
array_push( $buf, $table[$j >> 18 & 63], $table[$j >> 12 & 63], $table[$j >> 6 & 63], '=' );
}
return implode( "", $buf );
}
var_dump( array_to_base64_encode( array(1,2,3,4) ) ); // string(8) "AQIDBA=="
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment