{"id":3754,"date":"2021-01-14T04:30:04","date_gmt":"2021-01-14T04:30:04","guid":{"rendered":"https:\/\/studysection.com\/blog\/?p=3754"},"modified":"2021-01-14T06:24:52","modified_gmt":"2021-01-14T06:24:52","slug":"tips-for-improving-php-code","status":"publish","type":"post","link":"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/","title":{"rendered":"Tips for improving PHP code"},"content":{"rendered":"<h2>Problem 1: Not using PHP built-in function<\/h2>\n<p>Sometimes we try to solve the small problem with our own function instead of a built-in PHP function that provides the functionality.<\/p>\n<p><strong>Solution:<\/strong><br \/>\nPHP provides many useful functions that remove the need to \u201crefresh the wheel\u201d, and will often complete the work much better than anything typed by a standard program. Therefore, if you are experiencing the need to write complex tasks that you think may already exist, it is best to search the Internet (and PHP scripts in particular) before you start writing your code.<\/p>\n<h3>Problem 2: Using Magic Numbers and Strings<\/h3>\n<p>A magic number is a number in code which does not have any explanation and name. For example: in the following code, 10 is a magic number:<\/p>\n<p><code>&lt;?php<br \/>\nfor($i=1; $i<10; $i++)\n{\n     \/\/code;\n}<\/code><\/p>\n<p>In this code, it is not clear why it will execute 10 times.<\/p>\n<p><strong>Solution:<\/strong><br \/>\nTo make it meaningful and readable we can give the variable with a useful name. For example:<br \/>\n<code>&lt;?php<br \/>\n$checks=10;<br \/>\nfor($i=1; $i<$checks; $i++)\n{\n      \/\/your code;\n}<\/code><br \/>\nSimilarly, magic strings are the strings in the code which do not have any explanation. In this case also, it is recommended to set a meaningful name for a variable.<\/p>\n<h3>Problem 3: Not creating functions<\/h3>\n<p>Not creating functions is a typical problem for developers mainly for beginners. The problem stems from the fact that a programmer can write multiple lines of PHP scripts without having to encrypt parts of the code into tasks. This is problematic because it is difficult to understand what the code actually does without going deeper into it, and the developer may repeat himself unintentionally.<\/p>\n<p><strong>Solution:<\/strong><br \/>\nDividing the functions into small individual functions is a good solution to this problem.<\/p>\n<h3>Problem 4: Code Duplication<\/h3>\n<p>If you are writing the same code more than one or two times then there will be something wrong with the code. In this way you are violating the important rule of modern code writing: <strong>Do not Repeat Yourself (DRY)<\/strong>. This is important because if the code is finished and one code is written more than one time and after that, if there need to make changes, then you have to make more efforts to make changes in all the places.<\/p>\n<p><strong>Solution:<\/strong><br \/>\nWrap the code in a function is a good way to avoid duplication. Then the function can be called whenever needed.<\/p>\n<h3>Problem 5: Functions that do more than one thing<\/h3>\n<p>An effective function can do only one job and it can be called from different places in the code because it is ideal and performs a specific functioning for which task it is created.<br \/>\n<code>function phone_number($number)<br \/>\n{<br \/>\n  $digits = preg_replace('\/[^0-9]\/','',$number);<br \/>\n  $len = strlen($digits);<br \/>\n  $isValidPhoneNumber = ($len >= 7 && $len <= 14);      \n    if(!$isValidPhoneNumber) $digits = \"Not a phone number\";      \n  \/\/ return the phone number wrapped in html\n  return \"&lt;p>{$digits}&lt;\/p>\";<br \/>\n}<br \/>\nvar_dump(phone_number(\"1-800-123-4567\"));<br \/>\nvar_dump(phone_number(\"1-800-123-45678910\"));<\/code><\/p>\n<p>Answer is <\/p>\n<p><em>string '&lt;p>18001234567&lt;\/p>' (length=18)<br \/>\nstring '&lt;p>Not a phone number&lt;\/p>' (length=25)<\/em><\/p>\n<p>As we can see, the function validates the phone number and then wraps the result in HTML. This means that we cannot use the function every time we want to check the validity of a phone number because it does not return a boolean (true or false) value, but returns HTML. The effect is serious because we have to repeat ourselves and rewrite the authentication code repeatedly in each application which requires checking the validity of a phone number.<\/p>\n<p><strong>Solution:-<\/strong> Write down the code into a separate function. The first is check validation and the second is wrap in HTML.<br \/>\n<code>function validate_Phone_Number($string)<br \/>\n{<br \/>\n     \/\/replace all the non-digit characters<br \/>\n     $onlyDigits = preg_replace('\/[^0-9]\/','',$string);<br \/>\n     \/\/ check if the remaining string is 7-14 characters long and return boolean (true\/false) value<br \/>\n     $onlyDigitsLen = strlen($onlyDigits);<br \/>\n     return $isValidPhoneNumber = ($onlyDigitsLen >= 7 && $onlyDigitsLen <= 14);\n} \nfunction wrapInHtml($string)\n{\n     \/\/ return the string wrapped in html\n     return \"&lt;p>{$string}&lt;\/p>\";<br \/>\n}<br \/>\n\/\/ check the two functions<br \/>\n$string = \"1-800-123-4567\";<br \/>\n$isValidPhoneNumber = validate_Phone_Number($string);<br \/>\nvar_dump(($isValidPhoneNumber)? wrapInHtml($string) : wrapInHtml(\"Not a valid phone number\"));<\/code><\/p>\n<h3>Problem 6: Too many nested conditions<\/h3>\n<p>Many times, the use of nested conditions (like nested if-else condition) makes the code disorganized and difficult to read.<\/p>\n<p><strong>Example:<\/strong><br \/>\n<code>$code==='z';<br \/>\nif($code==='a' || $code==='b')<br \/>\n{<br \/>\n     if($code==='a')<br \/>\n     {<br \/>\n          echo \"a\";<br \/>\n     }<br \/>\n      if($code==='b')<br \/>\n      {<br \/>\n           echo \"b\";<br \/>\n      }<br \/>\n}<br \/>\nelse<br \/>\n{<br \/>\n    echo \"empty\";<br \/>\n}<\/code><br \/>\n<em>Answer:  empty<\/em><\/p>\n<p><strong>Solution:<\/strong><br \/>\nThis problem can be solved with the use of function and return statement in the code. For example:<br \/>\n<code>function removeNested($code)<br \/>\n{<br \/>\n  if($code==='a') return \"a\";<br \/>\n  if($code==='b') return \"b\";<br \/>\n  return \"empty\";<br \/>\n}<br \/>\n$code = \"z\";<br \/>\necho removeNested($code);<\/code><\/p>\n<h3>Problem 7: Vague names for functions and variables<\/h3>\n<p>Another problem that seems to exist even within the experienced system is that of the fixed and unambiguous words that do not change variables and function. For example, a job name like \"doSomething\" is not very clear. The problem may be due to a number of reasons: a lack of awareness, laziness, or the result of an activity that was written to perform a particular action, but which ended up taking another action instead. It creates the problem of readability of the code and makes it difficult in maintaining and making changes in the code.<\/p>\n<p><strong>Solution:<\/strong><br \/>\nThe solution is to assign an illustrative word that contains 2 to 3 words or more to function and variable names.<\/p>\n<p><small><em>Get certification for your knowledge in the fundamentals of Computer functioning by clearing the <a href=\"https:\/\/www.studysection.com\/computer-applications-diploma-advanced\">Computer Certification Exam<\/a>conducted by StudySection. After going through this Computer Certification exam, you will be able to evaluate your basic knowledge of computers.<\/em><\/small><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Problem 1: Not using PHP built-in function Sometimes we try to solve the small problem with our own function instead<\/p>\n","protected":false},"author":1,"featured_media":3755,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6],"tags":[591,200],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v21.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>StudySection Blog - Tips for improvement of PHP code<\/title>\n<meta name=\"description\" content=\"PHP provides many useful functions that remove the need to \u201crefresh the wheel\u201d. It often completes the work much better than standard program\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"StudySection Blog - Tips for improvement of PHP code\" \/>\n<meta property=\"og:description\" content=\"PHP provides many useful functions that remove the need to \u201crefresh the wheel\u201d. It often completes the work much better than standard program\" \/>\n<meta property=\"og:url\" content=\"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/\" \/>\n<meta property=\"og:site_name\" content=\"Blog Posts on famous people, innovations and educational topics\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/studysection\" \/>\n<meta property=\"article:published_time\" content=\"2021-01-14T04:30:04+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-01-14T06:24:52+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/01\/php.png\" \/>\n\t<meta property=\"og:image:width\" content=\"300\" \/>\n\t<meta property=\"og:image:height\" content=\"200\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"admin-studysection-blog\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@studysection\" \/>\n<meta name=\"twitter:site\" content=\"@studysection\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin-studysection-blog\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"1 minute\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/\"},\"author\":{\"name\":\"admin-studysection-blog\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402\"},\"headline\":\"Tips for improving PHP code\",\"datePublished\":\"2021-01-14T04:30:04+00:00\",\"dateModified\":\"2021-01-14T06:24:52+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/\"},\"wordCount\":748,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/studysection.com\/blog\/#organization\"},\"keywords\":[\"Cakephp\",\"php\"],\"articleSection\":[\"Learn and Grow\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/\",\"url\":\"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/\",\"name\":\"StudySection Blog - Tips for improvement of PHP code\",\"isPartOf\":{\"@id\":\"https:\/\/studysection.com\/blog\/#website\"},\"datePublished\":\"2021-01-14T04:30:04+00:00\",\"dateModified\":\"2021-01-14T06:24:52+00:00\",\"description\":\"PHP provides many useful functions that remove the need to \u201crefresh the wheel\u201d. It often completes the work much better than standard program\",\"breadcrumb\":{\"@id\":\"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/studysection.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Tips for improving PHP code\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/studysection.com\/blog\/#website\",\"url\":\"https:\/\/studysection.com\/blog\/\",\"name\":\"Blog Posts on famous people, innovations and educational topics\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/studysection.com\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/studysection.com\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/studysection.com\/blog\/#organization\",\"name\":\"StudySection\",\"url\":\"https:\/\/studysection.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png\",\"contentUrl\":\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png\",\"width\":920,\"height\":440,\"caption\":\"StudySection\"},\"image\":{\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/studysection\",\"https:\/\/twitter.com\/studysection\",\"https:\/\/www.instagram.com\/study.section\/\",\"https:\/\/www.linkedin.com\/company\/studysection\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402\",\"name\":\"admin-studysection-blog\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g\",\"caption\":\"admin-studysection-blog\"},\"url\":\"https:\/\/studysection.com\/blog\/author\/admin-studysection-blog\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"StudySection Blog - Tips for improvement of PHP code","description":"PHP provides many useful functions that remove the need to \u201crefresh the wheel\u201d. It often completes the work much better than standard program","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/","og_locale":"en_US","og_type":"article","og_title":"StudySection Blog - Tips for improvement of PHP code","og_description":"PHP provides many useful functions that remove the need to \u201crefresh the wheel\u201d. It often completes the work much better than standard program","og_url":"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/","og_site_name":"Blog Posts on famous people, innovations and educational topics","article_publisher":"https:\/\/www.facebook.com\/studysection","article_published_time":"2021-01-14T04:30:04+00:00","article_modified_time":"2021-01-14T06:24:52+00:00","og_image":[{"width":300,"height":200,"url":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/01\/php.png","type":"image\/png"}],"author":"admin-studysection-blog","twitter_card":"summary_large_image","twitter_creator":"@studysection","twitter_site":"@studysection","twitter_misc":{"Written by":"admin-studysection-blog","Est. reading time":"1 minute"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/#article","isPartOf":{"@id":"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/"},"author":{"name":"admin-studysection-blog","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402"},"headline":"Tips for improving PHP code","datePublished":"2021-01-14T04:30:04+00:00","dateModified":"2021-01-14T06:24:52+00:00","mainEntityOfPage":{"@id":"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/"},"wordCount":748,"commentCount":0,"publisher":{"@id":"https:\/\/studysection.com\/blog\/#organization"},"keywords":["Cakephp","php"],"articleSection":["Learn and Grow"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/","url":"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/","name":"StudySection Blog - Tips for improvement of PHP code","isPartOf":{"@id":"https:\/\/studysection.com\/blog\/#website"},"datePublished":"2021-01-14T04:30:04+00:00","dateModified":"2021-01-14T06:24:52+00:00","description":"PHP provides many useful functions that remove the need to \u201crefresh the wheel\u201d. It often completes the work much better than standard program","breadcrumb":{"@id":"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/studysection.com\/blog\/tips-for-improving-php-code\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/studysection.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Tips for improving PHP code"}]},{"@type":"WebSite","@id":"https:\/\/studysection.com\/blog\/#website","url":"https:\/\/studysection.com\/blog\/","name":"Blog Posts on famous people, innovations and educational topics","description":"","publisher":{"@id":"https:\/\/studysection.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/studysection.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/studysection.com\/blog\/#organization","name":"StudySection","url":"https:\/\/studysection.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png","contentUrl":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png","width":920,"height":440,"caption":"StudySection"},"image":{"@id":"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/studysection","https:\/\/twitter.com\/studysection","https:\/\/www.instagram.com\/study.section\/","https:\/\/www.linkedin.com\/company\/studysection"]},{"@type":"Person","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402","name":"admin-studysection-blog","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g","caption":"admin-studysection-blog"},"url":"https:\/\/studysection.com\/blog\/author\/admin-studysection-blog\/"}]}},"views":235,"_links":{"self":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/3754"}],"collection":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/comments?post=3754"}],"version-history":[{"count":3,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/3754\/revisions"}],"predecessor-version":[{"id":3757,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/3754\/revisions\/3757"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/media\/3755"}],"wp:attachment":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/media?parent=3754"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/categories?post=3754"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/tags?post=3754"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}