欢迎访问宙启技术站
智能推送

10个常用的PHP函数及其实现

发布时间:2023-06-03 05:43:08

1. strlen():计算字符串长度

实现方法:

function my_strlen($str) {
    $len = 0;
    while (isset($str[$len])) {
        $len++;
    }
    return $len;
}

2. substr():截取字符串

实现方法:

function my_substr($str, $start, $length = null) {
    if ($length === null) {
        $length = my_strlen($str) - $start;
    }
    $result = '';
    for ($i = $start; $i < $start + $length; $i++) {
        $result .= $str[$i];
    }
    return $result;
}

3. strpos():查找字符串中某个字符或子串的位置

实现方法:

function my_strpos($haystack, $needle, $offset = 0) {
    for ($i = $offset; $i < my_strlen($haystack); $i++) {
        if (my_substr($haystack, $i, my_strlen($needle)) === $needle) {
            return $i;
        }
    }
    return false;
}

4. count():计算数组长度

实现方法:

function my_count($array) {
    $count = 0;
    foreach ($array as $item) {
        $count++;
    }
    return $count;
}

5. array_push():向数组末尾添加一个或多个元素

实现方法:

function my_array_push(&$array, ...$values) {
    foreach ($values as $value) {
        $array[] = $value;
    }
    return my_count($array);
}

6. array_pop():弹出数组末尾的元素

实现方法:

function my_array_pop(&$array) {
    if (my_count($array) > 0) {
        $value = $array[my_count($array) - 1];
        unset($array[my_count($array) - 1]);
        return $value;
    } else {
        return null;
    }
}

7. sort():对数组进行排序

实现方法:

function my_sort(&$array) {
    for ($i = 0; $i < my_count($array); $i++) {
        for ($j = $i + 1; $j < my_count($array); $j++) {
            if ($array[$i] > $array[$j]) {
                $temp = $array[$i];
                $array[$i] = $array[$j];
                $array[$j] = $temp;
            }
        }
    }
}

8. header():设置HTTP头部信息

实现方法:

function my_header($key, $value) {
    header("$key: $value");
}

9. file_get_contents():读取文件内容

实现方法:

function my_file_get_contents($filename) {
    $handle = fopen($filename, 'r');
    $content = '';
    while (!feof($handle)) {
        $content .= fgets($handle);
    }
    fclose($handle);
    return $content;
}

10. file_put_contents():写入文件内容

实现方法:

function my_file_put_contents($filename, $content) {
    $handle = fopen($filename, 'w');
    fwrite($handle, $content);
    fclose($handle);
}