php get string length and replace first and last 3 characters WITHOUT using a function

Solution:1

Universal solution:

$string = "123456789";
$i = 0;
$limit = 3;
while (isset($string[$i])) {
    if ($i < $limit) {
        $string[$i] = '*';
    }
    $i++;
}
// you can rewrite this as loop
$string[$i - 1] = '*';
$string[$i - 2] = '*';
$string[$i - 3] = '*';

Starting with php7.1 where negative string indexes are allowed:

$string = "123456789";
// you can rewrite it to a loop too
$string[0] = $string[1] = $string[2] = $string[-1] = $string[-2] = $string[-3] = '*';
echo $string;

Solution without any function, but it emits PHP Notice, you can supress it with @:

$string = "123456789";
$i = 0;
$limit = 3;
while (true) {
    if ($string[$i] == '') {
        break;
    }

    if ($i < $limit) {
        $string[$i] = '*';
    }
    $i++;
}
/* Simplified version:
while ($string[$i] != '') {
    if ($i < $limit) {
        $string[$i] = '*';
    }
    $i++;
}
*/
$string[$i - 1] = '*';
$string[$i - 2] = '*';
$string[$i - 3] = '*';

echo $string;

Solution:2

I don’t know why you don’t want to use any PHP functions. However, it is still possible.

   <?php

function privacy($string)
{

    //get the string length   

    $i = 0;

    /*  
    while (isset($string[$i])) {
    $i++;
    }
    */

    while ($string[$i] !== "") {
        $i++;
    }

    //replace the first and last 3 characters of the $string with a star
    //if the length is bigger than or equals to 6
    if ($i >= 6) {
        for ($x = 0; $x < 3; $x++) {
            $string[$x]      = "*";
            $string[$i - $x] = "*";
        }
    }
    return $i . "<br>" . $string;
}

echo privacy("123456789");

?>

Will echo out this

 9
 ***456***

I think it is the easiest way to get the string length and replace the first and last 3 characters without confusion. So far!