Thread: Loop problem

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    24
    Rep Power
    0

    Loop problem


    PHP Code:
    for($i=0$i<$count;$i++){
    if(
    $var[$i]==$str)
    {
    echo 
    "$str".$var[$i];
    $strfirstlettercaps strtolower($str);
    $var1=$strfirstlettercaps.".php";
    require_once 
    $var1;  
    }
    else 
    {
    $strfirstlettercaps="";
    $var1=fopen("$strfirstlettercaps".".php","x+");
    echo 
    "<img src='../uc1.jpg'>";

    please anyone tell me wat i'm doing wrog here. The loop is entering in both if and else condition. BUt what i need to do is if the condition satisfies it should enter the if, and if it not satisfied then it should enter the else condition. Any ideas please tell me.
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Hi,

    that looks like a logical error. Obviously your loop will check the condition on each run, so every time either the "if" part or the "else" part will be executed.

    But I guess you want something like:
    If any element of $var equals $str, then run the first part, otherwise run the second part.

    And that's what in_array is for.

    Your programming style generally is a bit weird. You might wanna improve the following things:
    • Use sensible variable names. Variables like "$var", "$var1" and "$str" tell you nothing about what they actually contain and what they're for. This makes the code very difficult to read. And $strfirstlettercaps for a lowercase(!) string is just weird.
    • Get rid of this low level programming style. Use "foreach" instead of "for" when you want to iterate through an array. Use built-in arrays functions instead of reinventing the wheel.
    • Get rid of this "$variable" stuff (a string with a variable as its only contant). PHP does automatic type conversions, so this is completely useless 99% of the time. In the rare case you actually need an explicit type cast, use (string) $var.
    • Try to structure your code in a logical and intuitive way. Things like "If x, then require a file, otherwise output an image" don't really make sense. It's also not a good idea to use the same variable for two completely different types. In your case, $var1 can either hold a file name or a resource. How is that supposed to work in your later code?
    • Indent your code!
    Last edited by Jacques1; February 15th, 2013 at 01:00 AM.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".

IMN logo majestic logo threadwatch logo seochat tools logo