Quantcast
Channel: Lightningspirit's Blog
Viewing all articles
Browse latest Browse all 9

Array Implode for PHP

$
0
0

Here is a function to implode and array including the key and value pair.

<!--?php-->
 /**
 * Implode an array with the key and value pair giving
 * a glue, a separator between pairs and the array
 * to implode.
 * @param string $glue The glue between key and value
 * @param string $separator Separator between pairs
 * @param array $array The array to implode
 * @return string The imploded array
 */
 function array_implode( $glue, $separator, $array ) {
 if ( ! is_array( $array ) ) return $array;
 $string = array();
 foreach ( $array as $key => $val ) {
 if ( is_array( $val ) )
 $val = implode( ',', $val );
 $string[] = "{$key}{$glue}{$val}";
}
 return implode( $separator, $string );
}
 ?>

You can, for example, encode an array to be sent as an URL query using this:
php
$query = url_encode( array_implode( ’=', ’&’, $array ) );
?>

Or if you want to output an HTML element attributes:
php
echo ’<input ‘.array_implode( ’=”‘, ’” ‘, $array ).’ />’;
?>


Viewing all articles
Browse latest Browse all 9

Latest Images

Trending Articles