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
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
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:
for more info here is the link: array_search refrence