PHP Cheat Sheet


  // Comments in PHP
  
  // Comments are used to annotate code, making it easier to understand.
  // They are ignored by the PHP interpreter and do not affect the execution of the code.
  
  // Single-line Comments
  
  // Single-line comments start with // or # and extend to the end of the line.
  
  echo "Hello, World!";  // This is a single-line comment using //
  
  // The following line is also a single-line comment using #
  # echo "This line will not execute";
  
  // Multi-line Comments
  
  /* 
     Multi-line comments start with /* and end with */.
     They can span multiple lines and are useful for longer explanations or 
     commenting out blocks of code.
  */
  
  echo "This code will run";  /* This is a multi-line comment that
                                spans several lines.
                                echo "This code will not run"; */
  
  // Nested Comments (Not allowed in PHP)
  
  /* 
     PHP does not support nested multi-line comments.
     The following example will cause a syntax error:
  
     /*
        This is a nested comment block
        echo "This will cause an error";
     */
     echo "This will also cause an error";
  */
  
  /* To comment out a block of code that already contains comments,
     use single-line comments or carefully place multi-line comments. */
  
  // Example:
  
  /* This is a block comment
     // nested single-line comment is fine
     echo "This will not cause an error";
  */
  
  /* Properly closing a multi-line comment is crucial.
     Uncommenting the below code without fixing the comment ending will result in an error.
     echo "PHP requires careful handling of multi-line comments.";
  */
  
  /* It's common to use comments for:
     - Describing the purpose of a code block
     - Explaining complex logic
     - Temporarily disabling code
     - Adding notes and reminders */
  
  // Documentation Comments
  
  /** 
   * PHP also supports special documentation comments starting with /**.
   * These are often used to document functions, classes, and methods.
   * Documentation comments can be processed by tools like PHPDoc to generate API documentation.
   */
  
   /**
    * Adds two numbers and returns the result.
    *
    * @param int $a The first number.
    * @param int $b The second number.
    * @return int The sum of the two numbers.
    */
   function add($a, $b) {
       return $a + $b;
   }
  
  echo add(5, 10); // Output: 15
  
© 2024 CheatsheetCoder, All Rights Reserved.