Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

3 snippets
  • Removing all files from a folder using PHP

    <?php 
    
    $folderPath = "/tmp/test-folder"; 
    
    // List of files inside the folder 
    $files = glob($folderPath.'/*'); 
     
    foreach($files as $file) { 
    	if(is_file($file)) 
    		// Delete the given file 
    		unlink($file); 
    } 
    
    echo "Files deleted";
    
    // php main.php
    // Files deleted

    PHP program to delete all files from a specified folder.

  • Binary search algorithm in PHP

    <?php 
      
    function binarySearch(array $arr, int $target): int 
    { 
        $low = 0; 
        $high = count($arr) - 1; 
          
        while ($low <= $high) {          
            // compute middle index 
            $mid = floor(($low + $high) / 2);  
      
            if ($arr[$mid] > $target) { 
                // search the left side of the array 
                $high = $mid -1; 
            } else if ($arr[$mid] < $target) { 
                // search the right side of the array 
                $low = $mid + 1; 
            } else {
                // element found at mid 
                return $mid; 
            }
        } 
          
        // If we reach here element x doesnt exist 
        return -1; 
    } 
      
    // Driver code 
    $arr = [1, 2, 3, 4, 5]; 
    $target = 3;
    $result = binarySearch($arr, $target);
    
    if($result !== -1) { 
        echo "Target '$target' exists at position $result"; 
    } else {
        echo "Target '$target' does not exist";
    }

    Double search is a search method used to find an element in a sorted array.

  • Simple implementation of the Quick Sort algorithm in PHP

    <?php
    
    function quickSort(array $array): array
    {
        $length = count($array);
    
        if ($length <= 1) {
            return $array;
        }
    
        $pivot = $array[0];
        $left = $right = [];
    
        for ($i = 1; $i < $length; $i++) {
            if ($array[$i] < $pivot) {
                $left[] = $array[$i];
            } else {
                $right[] = $array[$i];
            }
        }
    
        return array_merge(quickSort($left), [$pivot], quickSort($right));
    }
    
    // Example usage:
    $array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
    $sortedArray = quickSort($array);
    
    echo "Original Array: " . implode(", ", $array) . "\n";
    echo "Sorted Array: " . implode(", ", $sortedArray) . "\n";
    
    

    Here's a simple implementation of the Quick Sort algorithm in PHP