Jerielle
Jerielle

Reputation: 7520

How can I find the last key of an associative array using PHP?

I have an array like this:

$breadcrumb = array(
    'home' => 'http://samplelink',
    'projects' => 'http://samplelink/projects',
    'project info' => 'http://samplelink/projects/3',
);

And I loop them:

<ol class="breadcrumb">
    <?php if(isset($breadcrumb)) { ?>
    <?php $last_key = end(array_keys($breadcrumb)); ?>
        <?php foreach($breadcrumb as $name => $link) { ?>
            <li><a href="<?php echo $link; ?>"><?php echo $name; ?></a></li>
        <?php } ?>
    <?php } ?>
</ol>

And I want to add a class='active' in the last li. How can I achieve that?

Upvotes: 0

Views: 389

Answers (3)

Mr. Engineer
Mr. Engineer

Reputation: 3515

You need end and key in order to get last key of array. Please try this code :

$breadcrumb = array(
    'home' => 'http://samplelink',
    'projects' => 'http://samplelink/projects',
    'project info' => 'http://samplelink/projects/3',
);

<ol class="breadcrumb">
    <?php if(isset($breadcrumb)) { ?>
    <?php 
    end($breadcrumb)
    $last_key = key($breadcrumb); 
    ?>
        <?php foreach($breadcrumb as $name => $link) { ?>
            <li><a href="<?php echo $link; ?>" <?php if($name==$last_key) { echo "active";}?>><?php echo $name; ?></a></li>
        <?php } ?>
    <?php } ?>
</ol>

1) end() advances array 's internal pointer to the last element, and returns its value.

2) key() returns the index element of the current array position.

Demo : https://eval.in/524280

Upvotes: 1

Kevin
Kevin

Reputation: 41885

One way would be just to add a ternary on the li tag:

<li <?php echo ($name === $last_key) ? 'class="active"' : ''; ?>><a href="<?php echo $link; ?>"><?php echo $name; ?></a></li>

Upvotes: 1

Drudge Rajen
Drudge Rajen

Reputation: 7987

You can check if $name==$last_key to make li class=active as below :

$breadcrumb = array(
    'home' => 'http://samplelink',
    'projects' => 'http://samplelink/projects',
    'project info' => 'http://samplelink/projects/3',
);

<ol class="breadcrumb">
    <?php if(isset($breadcrumb)) { ?>
    <?php $last_key = end(array_keys($breadcrumb)); ?>
        <?php foreach($breadcrumb as $name => $link) { ?>
            <li <?php if($name==$last_key){ ?>class="active"<?php }?> ><a href="<?php echo $link; ?>"><?php echo $name; ?></a></li>
        <?php } ?>
    <?php } ?>
</ol>

Upvotes: 2

Related Questions