Will Fris's WordPress Weblog











{20150810}   array_sprintf

Do you know of a quicker way to do this?
I’d be glad to know so šŸ™‚

The following code does a sprintf on a collection.


	if ( !function_exists( 'array_sprintf' ) ) {
		function array_sprintf ( $templateString , $inputArray ) {
			reset( $inputArray );
			while ( $i = each( $inputArray ) ) {
				if ( !is_array( $i[ 'value' ] ) ) {
					$i[ 'value' ] = array( $i[ 'value' ] );
				}
				array_unshift( $templateString , $i[ 'value' ] );
				$inputArray[ $i[ 'key' ] ] = call_user_func_array(
					'sprintf'
					, $i[ 'value' ]
				);
			}
			return $inputArray;
		}
	}

Obligatory example:


	$tags = array(
		array( 'href' => 'https://willfris.wordpress.com/' , 'txt' => 'This blog' )
		, [ 'http://willfris.nl/' , 'A site' ] # shorthand array-syntax
	);
	$element = [ '<li>' , '</li>' ];
	echo '<ul>' . $element[ 0 ]
		. implode(
			implode( $element )
			, array_sprintf( '<a href="%s">%s</a>' , $tags )
		)
		. $element[ 1 ] . '</ul>';


et cetera