3v4l.org

run code in 300+ PHP versions simultaneously
<?php function wp_create_links( $link_data ) { $links = array(); if ( isset( $link_data ) && is_array( $link_data ) ) { foreach ( $link_data as $key => $link ) { $attributes = array(); if ( isset( $link['attributes'] ) && is_array( $link['attributes'] ) ) { $attributes = $link['attributes']; } // URL check. if ( empty( $link['url'] ) || ! is_string( $link['url'] ) || '' === trim( $link['url'] ) ) { continue; } // Label check. if ( empty( $link['label'] ) || ! is_string( $link['label'] ) || '' === trim( $link['label'] ) ) { continue; } // Current check. if ( ! empty( $link['is_current'] ) && true === $link['is_current'] ) { $attributes['aria-current'] = 'page'; if ( empty( $attributes['class'] ) ) { $attributes['class'] = 'current'; } else { $attributes['class'] .= ' current'; } } // Collapse attributes to attribute="value" or boolean attributes. $attributes = array_map( function( $attribute, $value ) { // Mark invalid/empty attributes for removal. if ( empty( $attribute ) || ! is_string( $attribute ) ) { return false; } // Convert `int` and `float` values to `string`. if ( is_int( $value ) || is_float( $value ) ) { $value = (string) $value; } // Mark non-string values for removal. if ( ! is_string( $value ) ) { return false; } // On an empty `value`, assume this is a boolean attribute. if ( empty( $value ) ) { return $attribute; } return sprintf( '%s="%s"', $attribute, $value ); }, array_keys( $attributes ), array_values( $attributes ) ); // Clean up attributes. $attributes = array_filter( $attributes ); // Generate link. $links[ $key ] = sprintf( '<a href="%s"%s>%s</a>', $link['url'], ! empty( $attributes ) ? ' ' . implode( ' ', $attributes ) : '', $link['label'] ); } } return $links; } // Usage $links_data = array( 'author-link' => array( 'url' => 'https://example.org', 'label' => 'My Example Link', 'attributes' => array( 'class' => 'menu-link', 'rel' => 'author me', ), 'is_current' => true, ), 'external-link' => array( 'url' => 'https://example.com', 'label' => 'My Other Example Link', 'attributes' => array( 'class' => 'menu-link', 'rel' => 'external noreferer', ), ), ); $links = wp_create_links( $links_data ); // Want to wrap them with the key as the class? $menu = '<ul class="menu">'; foreach ( $links as $key => $link ) { $menu .= sprintf( '<li class="menu-item %s">%s</li>', $key, $link ); } $menu .= '</ul>'; echo $menu;
Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.27, 8.2.0 - 8.2.17, 8.3.0 - 8.3.4
<ul class="menu"><li class="menu-item author-link"><a href="https://example.org" class="menu-link current" rel="author me" aria-current="page">My Example Link</a></li><li class="menu-item external-link"><a href="https://example.com" class="menu-link" rel="external noreferer">My Other Example Link</a></li></ul>

preferences:
127.78 ms | 403 KiB | 117 Q