Skip to main content

PHP Basic Code Challenges

 Here are some PHP code challenges ranging from beginner to intermediate levels:

  1. String Manipulation Challenge:

// Write a function that:

// - Takes a string

// - Removes all vowels

// - Returns the modified string

function removeVowels($str) {

    return preg_replace('/[aeiou]/i', '', $str);

}

// Test case

echo removeVowels("hello world"); // Output: "hll wrld"


  1. Array Manipulation Challenge:

// Write a function that:

// - Takes an array of numbers

// - Returns only the unique numbers

// - Preserves the original order

function getUniqueNumbers($arr) {

    return array_values(array_unique($arr));

}


// Test case

$numbers = [1, 2, 2, 3, 4, 4, 5];

print_r(getUniqueNumbers($numbers)); // Output: [1, 2, 3, 4, 5]

  1. Prime Number Checker:

function isPrime($num) {

    if ($num <= 1) return false;

    for ($i = 2; $i <= sqrt($num); $i++) {

        if ($num % $i == 0) return false;

    }

    return true;

}


// Test cases

echo isPrime(7);   // Output: true

echo isPrime(10);  // Output: false

  1. Reverse Words Challenge:

function reverseWords($sentence) {

    $words = explode(' ', $sentence);

    $reversedWords = array_map('strrev', $words);

    return implode(' ', $reversedWords);

}


// Test case

echo reverseWords("Hello World PHP"); 

// Output: "olleH dlroW PHP"

  1. Palindrome Checker:

function isPalindrome($str) {

    $cleanStr = strtolower(preg_replace('/[^a-z0-9]/', '', $str));

    return $cleanStr === strrev($cleanStr);

}


// Test cases

echo isPalindrome("A man, a plan, a canal: Panama"); // Output: true

echo isPalindrome("race a car"); // Output: false

  1. Fibonacci Sequence Generator:

function generateFibonacci($n) {

    $fibonacci = [0, 1];

    for ($i = 2; $i < $n; $i++) {

        $fibonacci[] = $fibonacci[$i-1] + $fibonacci[$i-2];

    }

    return $fibonacci;

}


// Test case

print_r(generateFibonacci(10)); 

// Output: Array of first 10 Fibonacci numbers

  1. Object-Oriented Challenge:

class ShoppingCart {

    private $items = [];


    public function addItem($name, $price) {

        $this->items[$name] = $price;

    }


    public function removeItem($name) {

        unset($this->items[$name]);

    }


    public function getTotalPrice() {

        return array_sum($this->items);

    }

}


// Test usage

$cart = new ShoppingCart();

$cart->addItem('Apple', 0.5);

$cart->addItem('Banana', 0.3);

echo $cart->getTotalPrice(); // Output: 0.8

  1. Regular Expression Challenge:

function validateEmail($email) {

    return preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', $email);

}


// Test cases

echo validateEmail("test@example.com");     // Output: 1 (true)

echo validateEmail("invalid-email");        // Output: 0 (false)

  1. Date Manipulation:

function daysBetweenDates($date1, $date2) {

    $datetime1 = new DateTime($date1);

    $datetime2 = new DateTime($date2);

    $interval = $datetime1->diff($datetime2);

    return $interval->days;

}


// Test case

echo daysBetweenDates('2023-01-01', '2023-12-31'); 

// Output: Number of days between dates

  1. Nested Array Flattening:

function flattenArray($arr) {

    $result = [];

    array_walk_recursive($arr, function($a) use (&$result) { $result[] = $a; });

    return $result;

}


// Test case

$nestedArray = [1, [2, 3], [4, [5, 6]]];

print_r(flattenArray($nestedArray)); 

// Output: [1, 2, 3, 4, 5, 6]


Bonus Challenge Levels:

  • Beginner: Solve the function

  • Intermediate: Add error handling

  • Advanced: Optimize for performance

Recommended Learning Path:

  1. Understand the problem

  2. Write a basic solution

  3. Test with different inputs

  4. Add error handling

  5. Optimize if possible

Tips:

  • Use var_dump() or print_r() for debugging

  • Write unit tests

  • Consider edge cases

  • Practice regularly



Comments

Popular posts from this blog

MySQL's ACID compliance

Mysql acid compliance ACID is an acronym that stands for four key properties of database transactions: Atomicity Ensures that a transaction is treated as a single, indivisible unit of work Either all operations within a transaction are completed successfully, or none are If any part of the transaction fails, the entire transaction is rolled back to its previous state Prevents partial updates that could leave the database in an inconsistent state Consistency Guarantees that a transaction brings the database from one valid state to another valid state All data written to the database must adhere to defined rules, constraints, cascades, triggers, and other database integrity mechanisms Ensures that any transaction will not break the database's predefined rules Isolation Determines how and when changes made by one transaction become visible to other transactions Prevents interference between concurrent transactions MySQL provides different isolation levels: Read Uncommitted Read Commit...

PHP OOPs exercise - Basic Oops

  Here are key PHP OOP (Object-Oriented Programming) exercise questions with solutions: Basic Class and Object Exercise: // Create a simple bank account class class BankAccount {     private $accountNumber;     private $balance;     public function __construct($accountNumber, $initialBalance = 0) {         $this->accountNumber = $accountNumber;         $this->balance = $initialBalance;     }     public function deposit($amount) {         if ($amount > 0) {             $this->balance += $amount;             return true;         }         return false;  ...

Interview questions for Senior PHP Developer particle41.com

1.Self Introduction 2.Basic questions on session and cookie. 3.Where is session stored? 4.Difference between Cookie and session. 5.Will there be any session before session start? 6.Post Max execution time.How can we modify it? 7.We have a string, "BJFSJK".Without any php function reverse it with half the string length.   To reverse the string with half the string length without using any PHP functions, you can implement a simple algorithm to achieve the desired result. Here's how you can do it: Initialize two pointers, one at the beginning of the string and the other at the midpoint of the string. Swap characters between these two pointers iteratively, moving the pointers towards each other until they meet or cross each other. Here's the PHP code to implement this algorithm:  <?php $string = "ABC100"; $length = strlen($string); // Calculate the midpoint of the string $midpoint = (int)($length / 2); // Initialize pointers $start = 0; $end = $length - 1; //...