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
// Define a function named "test" that takes a parameter $str
function test($str) 
{
    // Check if the length of $str is less than 3 and it is equal to "C#",
    // or if the first two characters of $str are "C#" and the third character is a space.
    return (strlen($str) < 3 && $str == "C#") || (substr($str, 0, 2) == "C#" && substr($str, 2, 1) == ' ');
}

// Call the test function with argument "C# Sharp" and var_dump the result
var_dump(test("C# Sharp"));

// Call the test function with argument "C#" and var_dump the result
var_dump(test("C#"));

// Call the test function with argument "C++" and var_dump the result
var_dump(test("C++"));
?>

Sample Output:

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

Visual 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?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.