Created
February 4, 2014 04:29
-
-
Save mgng/8798175 to your computer and use it in GitHub Desktop.
array -> base64_encode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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