简体   繁体   中英

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?

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>

一种方法是在li标签上添加一个三进制:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM