How to find string length in php with out using strlen()? - php

How can you find the length of a string in php with out using strlen() ?

I know this is a pretty old issue, but this piece of code worked for me.
$s = 'string';
$i=0;
while ($s[$i] != '') {
$i++;
}
print $i;

$inputstring="abcd";
$tmp = ''; $i = 0;
while (isset($inputstring[$i])){
$tmp .= $inputstring[$i];
$i++;
}
echo $i; //final string count
echo $tmp; // Read string
while - Iterate the string character 1 by 1
$i - gives the final count of string.
isset($inputstring[$i]) - check character exist(null) or not.

I guess there's the mb_strlen() function.
It's not strlen(), but it does the same job (with the added bonus of working with extended character sets).
If you really want to keep away from anything even related to strlen(), I guess you could do something like this:
$length = count(str_split($string));
I'm sure there's plenty of other ways to do it too. The real question is.... uh, why?

Lets be silly
function stupidCheck($string)
{
$count = 0;
for($i=0; $i<66000; $i++)
{
if(#$string[$i] != "")$count++;
else break;
}
return $count;
}

Simply you can use the below code.
<?php
$string="Vasim";
$i=0;
while(isset($string[$i]))
{
$i++;
}
echo $i; // Here $i has length of string and the answer will be for this string is 5.
?>

The answer given by Vaibhav Jain will throw the following notice on the last index.
Notice: Uninitialized string offset
I would like to give an alternative for this:
<?php
$str = 'India';
$i = 0;
while(#$str[$i]) {
$i++;
}
echo 'Length of ' . $str . ' is ' . $i . '.';

mb_strlen — Get string length
$string ='test strlen check';
print 'mb_strlen(): ' . mb_strlen( $string, 'utf8' ) . "\n\n";
synatx: int mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] )
str - The string being checked for length.
encoding - The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

In newer PHP versions, you can use null coalescing operator to achieve this.
<?php
$string = 'test';
for($i = 0; ($string[ $i] ?? false) !== false; ++$i);
echo $i;// outputs length of the string.
Online Demo

You could also cheat with something like:
print strtok(substr(serialize($string), 2), ":");
Or this one is quite amusing:
print array_sum(count_chars($string));

function mystrlen($str)
{
$i = 0;
while ($str != '')
{
$str = substr($str, 1);
$i++;
}
return $i;
}

function findStringLength($string) {
$length = 0;
$lastStringChar1 = '1';
$lastStringChar2 = '2';
$string1 = $string . $lastStringChar1;
$string2 = $string . $lastStringChar2;
while ($string1[$length] != $lastStringChar1 || $string2[$length] != $lastStringChar2) {
$length++;
}
return $length;
}

You can use this code for finding string length without using strlen() function.
<?php
function stringlength($withoutstringlength)
{
$n = 0;
while(substr($withoutstringlength, $n, $n+1) != '')//General syntax substr(string,start,length)
{
$n++;
}
echo $n;
}
stringlength("i am a php dev");
?>

Try this:
function length($value){
if(empty($value[1])) return 1;
$n = 0;
while(!empty($value[$n+1])){
$n++;
}
return $n+1;
}

This doesn't use loops but may face the O(n) issue if strrpos uses strlen internally.
function length($str)
{
return strrpos($str.'_', '_', -1);
}

function my_strlen($str)
{
for($i=-1; isset($str[++$i]); );
return $i;
}
echo my_strlen("q");

$str = "Hello World";
$count= 0;
while( isset($str[$count]) && $str[$count] ) {
$count++;
}
echo $count;
OUTPUT:
11

Renverser un charactère sans Function
class StringFunction {
public function strCount($string) {
$cpt=0;
//isset pour cacher l'erreur
// Notice: Uninitialized string offset
while(isset($string[$cpt])) {
$cpt++;
}
return $cpt;
}
public function reverseChar($str) {
//mes indexes
$start = 0;
$end = $this->strCount($str)-1;
//Si $start est inférieur à $end
while ($start < $end) {
//change position du charactère
$temp = $str[$start];
$str[$start] = $str[$end];
$str[$end] = $temp;
$start++;
$end--;
}
return $str;
}
}
$string = "Bonjour";
$a = new StringFunction();
echo $string . "<br>";
echo $a->reverseChar($string);

This code will help you when you don't want to use any inbuilt function of php.
You can test this here also
http://phptester.net/
<?php
$stings="Hello how are you?";
$ctr=0;
while(1){
if(empty($stings[$ctr])){
break;
}
$ctr++;
}
echo $ctr;

<?php
$str = "aabccdab";
$i = 0;
$temp = array();
while(isset($str[$i])){
echo $str[$i];
$count = 0;
if(isset($temp[$str[$i]])){
$temp[$str[$i]] = $temp[$str[$i]]+1;
}else{
$temp[$str[$i]] = 1;
}
$i++;
}
print_r($temp);
?>

It's going to be a heavy work for your server, but a way to handle it.
function($string){
$c=0;
while(true){
if(!empty($string[$c])){
$c=$c+1;
} else {
break; // Prevent errors with return.
}
}
return $c;
}

$str = "STRING";
$i=0; $count = 0;
while((isset($str{$i}) && $str{$i} != "")){
$i++; $count++;
}
print $count;

This can also help -
$s = 'string';
$temp = str_split($s); // Convert a string to an array by each character
// if don't want the spaces
$temp = array_filter($temp); // remove empty values
echo count($temp); // count the number of element in array
Output
6

<?php
$arr = array('vadapalanai','annanager','chennei','salem','coimbatore');
$min = $arr[0];
$max = $arr[0];
foreach($arr as $key => $val){
if (strlen($min) > strlen($val)) {
$min = $val ;
}
if(strlen($max) < strlen($val)){
$max = $val;
}
}
echo "The shortest array length is : " .$min. " ".strlen($min);
echo "<br>";
echo "The longest array length is: " .$max. " ".strlen($max);
?>

$str = 'I am XYZ'
$count = 0;
$i=0;
while (isset($str[$i])) {
$count = $i;
$i++;
}
echo $count;

Related

Php Program to find Palindrome?

Three steps to find the palindrome?
use strrev on the given value
Then split using the str_split.
Then use foreach and concate the split value.
Example
$a = "madam";
$b = strrev($a);
$string_reverse = str_split($b);
$palin = '';
foreach($string_reverse as $value){
$palin.= $value;
}
print $palin;
if($a == $palin){
print "<br>Palindrome";
} else {
print "<br>Not Palindrome";
}
Output
madam
Palindrome
try this:
<?php
function check_plaindrome($string) {
//remove all spaces
$string = str_replace(' ', '', $string);
//remove special characters
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
//change case to lower
$string = strtolower($string);
//reverse the string
$reverse = strrev($string);
if ($string == $reverse) {
echo "<p>It is Palindrome</p>";
}
else {
echo "</p>Not Palindrome</p>";
}
}
$string = "A man, a plan, a canal, Panama";
check_plaindrome($string);
########Output#######
<p>It is Palindrome</p>
To check a string whether it is palindrome or not without PHP function.
<?php
$str = 'level';
$strLen = strlen($str)-1;
$revStr = '';
for($i=$strLen; $i>=0; $i--){
$revStr.=$str[$i];
}
if($revStr == $str)
echo 'Palindrome';
else
echo "Not Palindrome";
?>
function checkpala(string $input){
for( $i=0; $i < strlen($input); $i++){ //for each char in the string
if (substr($input,$i,1) != substr($input, strlen($input)-($i+1),1)){ //get the first char and the last char and compare them. Then get the 2nd and the 2nd from the end and compare them. repeate
//if at any point there is no match, stop checking, return false
//echo "$input is not a palindrome";
return false;
}
}
//if the loop completes and every character checked out, return true.
//echo "$input is a palindrome";
return true;
}
There is a simple way who we can write like this to don't make it complicate:
$a = "1681";
$b = strrev($a);
print $b;
if($a == $b){
print "<br>Plaindrome";
} else {
print "<br>Not Plaindrome";
}
You can try this, it reverses the string or value...
function fn_palindrome($palindrome) {
$reversed = '';
$original = $palindrome;
$string = array(); $j = 0;
$converted = (string) $palindrome;
$palindrome = str_split($converted);
$i = count($palindrome) - 1;
while($i >= 0) {
$string[$j] = $palindrome[$i];
$j++; $i--;
}
$reversed = implode('', $string);
if($reversed == $original) {
return TRUE;
} else {
return FALSE;
}
}
function checkPalindrome($string) {
return $string == strrev($string);
}
<?php
$word = "level"; // declare a varibale
echo "String: " . $word . "<br>";
$reverse = strrev($word); // reverse the word
if ($word == $reverse) // compare if the original word is same as the reverse of the same word
echo 'Output: This string is a palindrome';
else
echo 'Output: This is not a palindrome';
?>
Dummy String to be tested
$s = 'abcdefg';
Reverse the string order
$t = strrev($s);
Get the length of the string
$length = mb_strlen($s);
Variable to be used for concating string while traversing using for loop
$new = '';
Loop to traverse string
for ($i = 0; $i < $length; $i++) {
$new = $s[$i].$new;
}
Check string traversed using for loop is equal to string reversed using PHP function
if ($s == $new){
echo "Yes palindrome";
} else {
echo "No palindrome";
}
If output is yes then it is palindrome otherwise it is Not a palindrome string.
*** I have update the answer.
You can try the following code:
function checkPalindrome($string){
$string = strtolower($string);
$reverse = strrev($string);
if($string == $reverse){
return true;
} else {
return false;
}
}
Try this one..
<?php
$strng = 'SMS';
$rvsstr = '';
$i = 0;
while (!empty($strng[$i])) {
$rvsstr = $strng[$i].$rvsstr;
$i++;
}
// echo $rvsstr;
if ($strng === $rvsstr) {
echo "Number is Palindrome";
} else {
echo "Number is not palindrome";
}
?>
Could it be as simple as this?
function isPalindrome(string $word) : bool
{
$word = strtolower($word);
if(strrev($word) === $word){
return true;
} else {
return false;
}
}
echo isPalindrome('Deleveled');
People are already correct here, anyway simply you can try this.
function checkPalindrome($string) {
$string = strtolower($string);
return $string == strrev($string);
}
function isPalindrome($string): bool {
return strtolower($string) === strtolower(strrev($string));
}
Didn't find solution for my 'kąyąk' problem when You have different characters encoding.
Below is originally from php.net comment changed sligtly by me to see on xdebug in phpStorm whats going on.
public function isPalindrome(): bool {
$r = '';
for ($i = mb_strlen($this->string); $i >= 0; $i--) {
$r .= mb_substr($this->string, $i, 1);
}
for ($i = 0 ; $i <= strlen($r); $i++) {
$o = mb_substr($this->string, $i, 1); // original current char
$s = mb_substr($r, $i, 1); // inverted current char
if ($o != $s) {
return false; // if does not match return false
}
}
return true;
}
$a = readline("Enter word: ");
$i=0;
for ($i=0; $i < strlen($a) && substr($a,$i,1) == substr($a,strlen($a)-($i+1),1); $i++);
echo ($i == strlen($a))?"Pallindrome":"Not Pallindrome";
$i < strlen($a) && substr($a,$i,1) == substr($a,strlen($a)-($i+1),1)
This test is the key where the loop tries to keep checking if the characters starting from the left of the string matches with the characters from the right, and it should continue till all characters are checked or till it doesn't find a matching character.
So, first of all, what is palindrome?
Palindrome is a word, phrase, or sequence that reads the same backward as forward.
So, to know wether the string is a palindrome or not, we only need to reverse the original string and then compare it.
Let's say we want to check wether the string Level is a palindrome or not:
$str = 'Level';
This step is for ignoring the case-sensitivity so Level and level will be considered the same.
$str = strtolower($str);
Then we can use the strrev() to reverse the string, then compare it to the original as follow:
echo (strrev($str) === $str) ? 'Palindrome' : 'Not palindrome';
You can also write it with if-else block if you consider it easier to read:
if (strrev($str) === $str) {
echo "Palindrome";
} else {
echo "Not palindrome";
}
Final code:
$str = 'Level';
$str = strtolower($str);
echo (strrev($str) === $str) ? 'Palindrome' : 'Not palindrome';

Detecting a palindrome in php

I am trying to create a program which determines if a string is a palindrome or not.
This is the error i'm getting.
Notice: Array to string conversion in C:\wamp\www\task18.php on line 22
My code is below:
<?php
//TASK 18 PALINDROME
//use string split function to split a string into an array
$str = "Mum";
$str =strtolower($str);
$strArray = array();
$strArray = str_split($str);
$len = sizeof($strArray);
$reverseStr ="";
for($i=$len-1; $i>=0; $i--){
$reverseStr .=$strArray[$i];
}
if ($strArray == $reverseStr) {
echo " $strArray is a palindrome";
} else {
echo " $strArray is not a palindrome";
}
First of all, you're comparing a string ($reverseStr) to an array ($strArray).
You need to edit the code to this:
for($i=$len-1; $i>=0; $i--){
$reverseStr[] .=$strArray[$i];
}
This will then put the reversed word into an array. So mum would be correctly outputted as mum, and test would be tset, but in an array.
This will then make the if pass, but you can't echo an array, so you should just echo out $str.
Full code:
$str = "mum";
$str =strtolower($str);
$strArray = array();
$strArray = str_split($str);
$len = sizeof($strArray);
$reverseStr = array();
for($i=$len-1; $i>=0; $i--){
$reverseStr[] .=$strArray[$i];
}
if ($strArray == $reverseStr) {
echo "$str is a palindrome";
} else {
echo "$str is not a palindrome";
}
or if you need to use $strArray to be in the echo, you can use implode():
echo implode($strArray). " is/is not a palindrome";
If you want to make it shorter, you can use this:
$str = strtolower("Mum");
$strArray = str_split($str);
$len = sizeof($strArray);
$reverseStr = array();
for($i=$len-1; $i>=0; $i--)
$reverseStr[] .=$strArray[$i];
echo "$str is ".($strArray==$reverseStr ? "" : "not") . " a palindrome";
Description:- You can't Echo an array that's why you are getting this error.Because you are echoing a array which is not possible.Type Juggling(Variables are some time automatically cast to best fit).That's same happens with your code because you trying to echo a array and when php trying to convert it to string it fails.Here below is a code to check palidrome using str_split().
<?php
$word = strtolower("mum");
$splitted = str_split($word);
$reversedWord = "";
$length = strlen($word);
for($i = 0; $i < $length; $i++)
$reversedWord .= $splitted[$length - $i - 1];
echo $word == $reversedWord ? "It's a palindrome " : "It's not a palindrome";
?>
you can also use given thing without using any php function.
$str="level";
for($i=0;$i<40000;$i++)
if($str[$i])
$count++;
else
break;
for ($j=$count;$j >=0; $j--){
$newStr.=$str[$j];
}
//echo $newStr;
if($newStr==$str)
echo $newStr." is a palindrome";
else
echo $newStr." is not a palindrome";
?>
You might want to try this, it works...
function fn_palindrome($palindrome) {
$reversed = '';
$original = $palindrome;
$string = array(); $j = 0;
$converted = (string) $palindrome;
$palindrome = str_split($converted);
$i = count($palindrome) - 1;
while($i >= 0) {
$string[$j] = $palindrome[$i];
$j++; $i--;
}
$reversed = implode('', $string);
if($reversed == $original) {
return TRUE;
} else {
return FALSE;
}
}

Return every other character from string in PHP

Assume I have a string variable:
$str = "abcdefghijklmn";
What is the best way in PHP to write a function to start at the end of the string, and return every other character? The output from the example should be:
nljhfdb
Here is what I have so far:
$str = "abcdefghijklmn";
$pieces = str_split(strrev($str), 1);
$return = null;
for($i = 0; $i < sizeof($pieces); $i++) {
if($i % 2 === 0) {
$return .= $pieces[$i];
}
}
echo $return;
Just try with:
$input = 'abcdefghijklmn';
$output = '';
for ($i = strlen($input) - 1; $i >= 0; $i -= 2) {
$output .= $input[$i];
}
Output:
string 'nljhfdb' (length=7)
You need to split the string using str_split to store it in an array. Now loop through the array and compare the keys to do a modulo operation.
<?php
$str = "abcdefghijklmn";
$nstr="";
foreach(str_split(strrev($str)) as $k=>$v)
{
if($k%2==0){
$nstr.= $v;
}
}
echo $nstr; //"prints" nljhfdb
I'd go for the same as Shankar did, though this is another approach for the loop.
<?php
$str = "abcdefghijklmn";
for($i=0;$i<strlen($str);$i++){
$res .= (($i-1) % 2 == 0 ? $str[$i] : "");
}
print(strrev($res)); // Result: nljhfdb
?>
reverse the string then do something like
foreach($array as $key => $value)
{
if($key%2 != 0) //The key is uneven, skip
continue;
//do your stuff
}
loop forward, append backward
<?php
$res = '';
$str = "abcdefghijklmn";
for ($i = 0; $i < strlen($str); $i++) {
if(($i - 1) % 2 == 0)
$res = $str[$i] . $res;
}
echo $res;
?>
preg_replace('/(.)./', '$1', strrev($str));
Where preg_replace replaces every two characters of the reversed string with the first of the two.
How about something like this:
$str = str_split("abcdefghijklmn");
echo join("",
array_reverse(
array_filter($str, function($var) {
global $str;
return(array_search($var,$str) & 1);
}
)
)
);

PHP Combine two strings

Is there a way in php to make two strings combine to one? I want to combine strings with the same size together?
$string1 = "apple"
$string2 = "block"
//FUNCTION STUFF HERE
$output = "abplpolcek";
You could try this:
$output='';
for($i=0;$i<strlen($string1);$i++)
{
$output.=$string1[$i];
$output.=$string2[$i];
}
echo $output;
Or you can write a simple function like this:
function funnyConcatStrings($str1, $str2)
{
$output='';
$leng=strlen($str1);
if(strlen($str1)==strlen($str2))
{
for($i=0;$i<$leng;$i++)
{
$output.=$str1[$i];
$output.=$str2[$i];
}
}
else
{
$output='Strings were not equal.\n';
}
return $output;
}
// Use it like this:
$mashedString=funnyConcatStrings($string1, $string2);
// or
echo funnyConcatStrings($string1, $string2);
$str_length = 5;
$output = '';
for($i = 0; $i < $str_length; $i++)
{
$output .= $string1[$i] . $string2[$i];
}
use for instance $string1[0] ( letter 'a' ) to access the first letter and make a for loop
Really easy;
$a = 'abcdef';
$b = 'ghijkl';
$l = strlen($a);
$s='';
for($i=0;$i<$l;$i++)$s .= $a[$i] + $b[$i];
echo $s;
1.) Check if the string have the same lengts with strlen
2.) Then you can iterate through the string and access them as an array
$string = 'test123';
echo $string[0] -> 't'
Then you can combine the string and safe them in a new variable.
This will work for strings that are different lenght as well
$string1 = "apple";
$string2 = "block";
$arr1 = str_split($string1);
$arr2 = str_split($string2);
if(count($arr1) > 0)
{
foreach($arr1 as $key => $value)
{
$_tmp[] = $value;
if(isset($arr2[$key]))
{
$_tmp[] = $arr2[$key];
}
}
}
else
{
$key = 0;
}
if($key + 1 < count($arr2))
{
for($i = $key + 1; $i < count($arr2); $i++)
{
$_tmp[] = $arr2[$key];
}
}
echo implode("", $_tmp);
echo str_shuffle("apple" . "block");
result: aekbplopcl

How to remove characters from a string?

(my first post was not clear and confusing so I've edited the question)
I was studying string manipulation.
You can use strlen() or substr() but cannot rely on other functions that are predefined in libraries.
Given string $string = "This is a pen", remove "is" so that
return value is "Th a pen" (including 3 whitespaces).
Remove 'is' means if a string is "Tsih", we don't remove it. Only "is" is removed.
I've tried (shown below) but returned value is not correct. I've run test test and
I'm still capturing the delimiter.
Thanks in advance!
function remove_delimiter_from_string(&$string, $del) {
for($i=0; $i<strlen($string); $i++) {
for($j=0; $j<strlen($del); $j++) {
if($string[$i] == $del[$j]) {
$string[$i] = $string[$i+$j]; //this grabs delimiter :(
}
}
}
echo $string . "\n";
}
Clarifying, the original quiestion is not Implement a str_replace, It's remove 'is' from 'this is a pen' without any functions and no extra white spaces between words. The easiest way would be $string[2] = $string[3] = $string[5] = $string[6] = '' but that would leave an extra white space between Th and a (Th[ ][ ]a).
There you go, no functions at all
$string = 'This is a pen';
$word = 'is';
$i = $z = 0;
while($string[$i] != null) $i++;
while($word[$z] != null) $z++;
for($x = 0; $x < $i; $x++)
for($y = 0; $y < $z; $y++)
if($string[$x] === $word[$y])
$string[$x] = '';
If you were allowed to use substr() it'd be so much easier. Then you could just loop it and check for the matched value, why can't you use substr() but you can strlen() ?
But without, this works at least:
echo remove_delimiter_from_string("This is a pen","is");
function remove_delimiter_from_string($input, $del) {
$result = "";
for($i=0; $i<strlen($input); $i++) {
$temp = "";
if($i < (strlen($input)-strlen($del))) {
for($j=0; $j<strlen($del); $j++) {
$temp .= $input[$i+$j];
}
}
if($temp == $del) {
$i += strlen($del) - 1;
} else {
$result .= $input[$i];
}
}
return $result;
}
The following code can also used to replace the sub string:
$restring = replace_delimiter_from_string("This is a pen","is", "");
var_dump($restring);
$restring = replace_delimiter_from_string($restring," ", " ");
var_dump($restring);
function replace_delimiter_from_string($input, $old, $new) {
$input_len = strlen($input);
$old_len = strlen($old);
$check_len = $input_len-$old_len;
$result = "";
for($i=0; $i<=$check_len;) {
$sub_str = substr($input, $i, $old_len);
if($sub_str === $old) {
$i += $old_len;
$result .= $new;
}
else {
$result .= $input[$i];
if($i==$check_len) {
$result = $result . substr($input, $i+1);
}
$i++;
}
}
return $result;
}

Categories