skip to Main Content

I am fairly new to PHP, just started learning and I have written the below code:

The output of the above code is: Doesnt exist1Doesnt exist

I understand that this happened because of foreach loop, how do I avoid this without using for loop?

Also, my desired output is only the key, i.e: 1, in this case.

TIA

Raksha

<?php
       $programmingLanguages = ['php','java','giga'];
         foreach ($programmingLanguages as $key => $language){
         if($language=='java'){
            echo $key;
        }
        else
            echo 'Doesnt exist';
}
?>

2

Answers


  1. the code is checking whether each element in the array is equal to the string "java" since the first element is not equal to java the if condition fails

    <?php
       $programmingLanguages = ['php', 'java', 'giga'];
       $found = false;
       for($i = 0; $i < count($programmingLanguages); $i++){
          if($programmingLanguages[$i] == 'java'){
             echo $i;
             $found = true;
             break;
          }
       }
       if(!$found){
          echo 'Doesnt exist';
       }
    ?>
    
    Login or Signup to reply.
  2. a simpler method will be to use array_search() function. The array_search() function search an array for a value and returns the key.

    here is the example:

    <?php
           $programmingLanguages = ['php','giga','java'];
    
          $key = array_search('java',$programmingLanguages) ;
    
          echo $key;
    ?>
    

    for more info here is the link: array_search refrence

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search