Search code examples
phpreadabilitycode-readability

How to make this code more readable


This is a part fo php code, which use the contentArray, which is a JSON, and generate the UI to the user, it generate html tags, also, it generate js code too.... It works, but I think the code is pretty difficult to read and maintain, any ideas??? thank you.

for($i = 0; $i < count($contentArray); $i++){  

    if($i %2 == 0){
       echo ("<li class='even_row'>");
    }else{
       echo ("<li class='odd_row'>");
    }  
    $content = $contentArray[$i];    

    echo("<textarea class='userdata' id='user_data_textarea_".$content->{'m_sId'}."'>");
    echo($content->{'m_sDataContent'});  
    echo("</textarea>"); 

echo("</li>");   

    echo("<script type='text/javascript'>");

    echo("$('#user_data_textarea_".$content->{'m_sId'}."').bind('keydown', function(e){");  
    echo("  TypingHandler.handleTypingInUserDataTextArea(".$content->{'m_sId'}.", e);");
    echo(" });");    

    echo("</script>");

}            

Solution

  • first for your odd and even styling there is not need for a class just use css

    here is info on that

    then in php only echo what you need in one line

    $count = count($contentArray);
    for($i = 0; $i < $count; $i++){  
        $content = $contentArray[$i];    
        echo('<li><textarea class="userdata" id="user_data_textarea_"'.$content->{'m_sId'}.'">'.$content->{'m_sDataContent'}.'</textarea></li>');   
    }
    

    and lets put the jquery in the html page away from php

    we get can get every item by using starts with selector

    $('[id^=user_data_textarea_]').bind('keydown', function(e){  
        var id = this.id.str_replace("user_data_textarea","");
        TypingHandler.handleTypingInUserDataTextArea(id, e);
    });