Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello coders,
I am practicing foreach and nested if in php.
I am having a so called bug. The code is not working the way it should.
I have an array of cars and foreach statement that loops through these array elements.
Now i am using if statement that, if the car is bmw then replace it with best car in the world and if it is volkswagen then replace it with nation car. So far it works good until bmw is best car but it does not replace volkswagen with the nation car and instead it prints out the else statement and prints out that the cars not found. Please check the code below.
Also please tell me that, is it possible to replace audi with ferrari using recursive function? I mean, if i call a recursive function and when the audi is found, it replaces it with ferarri.

What I have tried:

PHP
<?php

$anarray= array('bmw','volkswagen','volvo','audi','bmw');

foreach($anarray as $value){
    
    echo 'The car is: '.$value.'.'.' ';
    
    
}
if($value == 'bmw')
    {
        echo 'bmw is the best car in the world.'.' '.' ';
        
        if($value == 'volkswagen')
    {
        echo 'volkswagen is a  nation car';
    }
    else{
        echo 'cars not found.';
    }
    }
    
    
    
    


?>
Posted
Updated 11-Sep-18 1:15am
v3

1 solution

The problem is the you can't "nest" it like that. Think about what you are doing:
C#
if (a == 1)
   {
   if (a == 2)
      {
      ...
      }
   }
If a is equal to 1, then by definition it can't be equal to 2 as well - maths just doesn't work like that!
So when you find a match with 'BMW' then by definition the same value cannot be 'volkswagen' as well!

What you need to use is elseif: PHP.net elseif/else if[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900