w3resource

PHP Exercises: Check if a given string starts with 'C#' or not

PHP Basic Algorithm: Exercise-12 with Solution

Write a PHP program to check if a given string starts with 'C#' or not.

Sample Solution:

PHP Code :

<?php
function test($str) 
{
   return (strlen($str) < 3 && $str=="C#") || (substr($str,0,2) == "C#" && substr($str,2,1) == ' ');
}

var_dump(test("C# Sharp"));
var_dump(test("C#"));
var_dump(test("C++"));

Sample Output:

bool(true)
bool(true)
bool(false)

Pictorial Presentation:

PHP Basic Algorithm Exercises: Check if a given string starts with 'C#' or not.

Flowchart:

Flowchart: Check if a given string starts with 'C#' or not.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new string taking the first 3 characters of a given string and return the string with the 3 characters added at both the front and back. If the given string length is less than 3, use whatever characters are there.
Next: Write a PHP program to check if one given temperatures is less than 0 and the other is greater than 100.

What is the difficulty level of this exercise?



PHP: Tips of the Day

$_REQUEST: This SuperGlobal Variable is used to collect data submitted by a HTML Form

Example:

This code save in a php file and run in the browser.

<!DOCTYPE html> 
<html> 
<body> 
  
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> 
 NAME: <input type="text" name="user"> 
 <button type="submit">SUBMIT</button> 
</form> 
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { 
    $name = htmlspecialchars($_REQUEST['user']); 
    if(empty($name)){ 
        echo "Name is empty"; 
    } else { 
        echo $name; 
    } 
} 
?> 
</body> 
</html> 

Output:

Owen