简体   繁体   中英

How to get a index of an array element

I need to get the index of the array element, in my case $ch is an array element, I need the index value (for eg: overview=array[0] , $arval = 0 ), so i could print the $tabs[$arval+1] .

<?php
$tab ='overview,gallery,video,songs$value1$value2$value3$value4';
$tabs = explode('$',$tab);
$tabname = explode(',',$tabs[0]);
echo '<div id="tab" style="float:left;width:100%;height:30px;background:#333">';
foreach($tabname as $i)
{
echo '<a id="'.$i.'" style="color:#fff;padding:2px 10px;" href="?tab='.$i.'" >'.$i.'</a>';
}
echo '</div>';


if(isset($_GET['tab']))
   {
       $ch=$_GET['tab'];
           foreach($tabname as $i){
              if ($ch == $i)

             // get the array index of the current element $arval
             // echo $tabs[$arval+1]

        }  }      ?>

How can I accomplish it?

foreach($tabname as $index => $i){
                    ^^^^^^^^^

In your foreach you need to do this:

foreach($tabname as $index => $value){
// $index is the index
// $value is the value

    if ($ch == $i)

        // get the array index of the current element $arval
        // echo $tabs[$arval+1]

} 

Maybe this could work for you:

if(isset($_GET['tab']))
{
       $ch=$_GET['tab'];
       if($key = array_search($ch, $tabname, true))
             // get the array index of the current element $arval
             echo $tabs[$key];

        }
}

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