Jessica
Jessica

Reputation: 449

Condensing PHP Arrays?

Hello I have the following code to generate my navigation/page menu along with applying a style element to the active page. I'd like to know how I can go about condensing the code rather than having two merging arrays?

Here's my current code, the difference between the two is the html link outputs. The 'Home' link needs to be <a href="./'. $k .'">'. $v .'</a>

Whereas the other pages need to have <a href="./?p='. $k .'">'. $v .'</a>

<?php

    $current = array(
    "" => "Home"
    );
    foreach( $current as $k => $v ) {
        $active = $_GET['p'] == $k
        ? ' class="current_page_item"'
        : '';
    echo '<li'. $active .'><a href="./'. $k .'">'. $v .'</a></li>';
    }

    $current = array(
        "contact" => "Contact Us",
        "about" => "About Us",
        "privacy" => "Privacy Policy"
    );
    foreach( $current as $k => $v ) {
        $active = $_GET['p'] == $k
            ? ' class="current_page_item"'
            : '';
        echo '<li'. $active .'><a href="./?p='. $k .'">'. $v .'</a></li>';
    }

?>

Any help would be much appreciated, thank you :)

Upvotes: 0

Views: 117

Answers (2)

sukinsan
sukinsan

Reputation: 513

Almost the same

$href =empty($k) ? "./" : "./?p={$k}" ;

Upvotes: 1

Jaroslav Moravec
Jaroslav Moravec

Reputation: 428

<?php

$current = array(
    "" => "Home"
    "contact" => "Contact Us",
    "about" => "About Us",
    "privacy" => "Privacy Policy"
);
foreach( $current as $k => $v ) {
    $active = $_GET['p'] == $k
        ? ' class="current_page_item"'
        : '';
    echo '<li'. $active .'><a href="./'.(empty($k)?"":"?p=") . $k .'">'. $v .'</a></li>';
}

?>

Upvotes: 1

Related Questions