Reputation: 97
My goal is to create a function that removes the first and last characters of a string in php.
My code:
function remove_char(string $s): string {
$len = strlen($s);
return substr($s,1,$len-2);
}
This not past the codewar code test. Can anyone tell me why it is not correct?
Upvotes: 0
Views: 224
Reputation: 1387
<?php
function remove($word){
$result = substr($word, 1, -1);
return $result;
}
$word = 'HELLO';
$results = remove($word);
echo $results;
?>
Upvotes: 0
Reputation: 11
try this code.
function remove_char(string $s){
if(strlen($s) > 1){
return substr($s, 1, -1);
}
return false;
}
Upvotes: 1
Reputation: 1042
The built in function substr is accepting negative value, when you use negative value it affect readability. You can also give the function name better and clearer name like so:
function modify_string(string $s): string {
return substr($s, 1, -1);
}
Upvotes: 1