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

Interview questions related to Laravel 8 updates- Laravel Interview questions

 Laravel 8 brought several updates and features to the framework. If you are preparing for an interview and expecting questions related to Laravel 8 updates, here are some potential questions: 1. What are the major features introduced in Laravel 8? Laravel Jetstream: A new application scaffolding for Laravel, providing teams with a starting point for building robust applications. Laravel Breeze: A lightweight and minimalistic front-end starter kit. Model Factory Classes: Introduction of factory classes for model factories, allowing for better organization of data seeding logic. Job Batching: A feature that allows you to easily run a batch of jobs and then perform some action when all the jobs have completed. Dynamic Blade Components: The ability to render Blade components dynamically. 2. Explain the improvements made to the Laravel job queue in version 8. Laravel 8 introduced Job Batching, which allows you to group multiple jobs into a batch and perform actions upon the completion ...

Vue Top Interview Questions

 1. Can you explain the Vue Composition API and its benefits? The Vue Composition API is a feature introduced in Vue 3 that revolutionizes the way we write Vue components by allowing us to compose our component logic using functions. Instead of scattering our component logic across various options like data, methods, computed, and watch, the Composition API encourages us to organize our logic into smaller, reusable functions called composition functions. One of the primary features of the Composition API is the setup() function. This function replaces the traditional options like data, methods, and others. Inside the setup() function, we can define reactive state using ref() and reactive() functions, set up lifecycle hooks using functions like onMounted(), and create computed properties and watchers using computed() and watch() functions. One significant benefit of the Composition API is better organization and reusability of code. By breaking our component logic into smaller funct...