Arun Killu Arun Killu - 1 month ago 20
PHP Question

string length not decremented when unset string index

I was trying to create palindrome by deleting one character from string at a time . While unsetting the string index .The string length is not getting reduced.

$s = "arun";
var_dump ($s);
$s[1] = NULL;
var_dump($s) ;


output



string(4) "arun"
string(4) "aun"


Why does the length not reduced.

Answer

because you are not in any way reducing your string, but just replacing one character.

your string gets transformed from a r u n to a (null) u n, which is still four chars long.

to achieve your goal, use substr_replace

<?php
$s = "arun";
var_dump ($s); //arun
$s = substr_replace($s, "", 1,1);
var_dump($s); //aun
Comments