Php Program to find Palindrome? - php

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';

Related

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;
}
}

Combining preg_match regex

I'm wondering if there is a way to somehow combine multiple regex statements into one? Maybe I could use an array, or can you purely do it with regex?
$reg = '/[a-zA-Z0-9]{7}$/';
$reg_l = '/[a-zA-Z0-9]{7}-lg$/';
$base = 'Fz4vqVW'; // May also be Fz4vqVW-lg
if (preg_match($reg,$base) { //Just checks for a 7 long string
echo '1';
} elseif (preg_match($reg_l,$base) { //Checks for 7 long string with -lg at the end
echo '2';
} else {
echo '0';
}
It can be combined in one regex with preg_replace_callback like this:
$reg = '/^(?:([a-zA-Z0-9]{7})(-lg)?|.*)$/';
$base = 'Fz4vqVW'; // May also be Fz4vqVW-lg
echo preg_replace_callback($reg, function($m) {
if (isset($m[2])) return 2; elseif (isset($m[1])) return 1; else return 0; }, $base);
Example Code:
$arr=array('Fz4vqVW', 'Fz4vqVW-lg', 'foobar');
foreach ($arr as $a) {
echo preg_replace_callback($reg, function($m) { if (isset($m[2])) return 2;
elseif (isset($m[1])) return 1; else return 0; }, $a)."\n";
}
Output:
1
2
0
You can also modify your preg_match() call as follows:
$reg = '/^[a-zA-Z0-9]{7}(-lg)?$/';
if (preg_match($reg, $base, $m))
echo isset($m[1]) ? 2 : 1; else echo 0;
You can simply count the number of items in the match result:
$base = 'Fz4vqVW';
$m = [];
preg_match('~^[a-zA-Z0-9]{7}(-lg)?$~D', $base, $m);
echo count($m);

count repeated occurrence of 0 & 1 in a string

Return false if the repeated occurrence of 0's or 1's in the string is greater than number($k).
I have written a function which works, but I need to optimize it:
<?php
function satisfied($str, $k){
$stream = $last = $str[0];
for($i = 1; $i <= strlen($str)-1; $i++){
if($str[$i] != $last) $last = $stream = $str[$i];
else $stream .= $str[$i];
if(strlen($stream) > $k) return false;
}
return true;
}
Example:
satisfied("0111", 2) - False
satisfied("0111", 3) - True
satisfied("00111000111", 3) - True
satisfied("00111000111", 4) - True
I wanted to know if I can do this with help of preg_match?
something like:
preg_match('/(0+|1+){'.$k.'}/', "0111");, this is not even close to what i want to achieve.
I want to avoid for loops to optimize the code. Will the preg_match be faster than the function above ? And obviously, you can also suggest me tweaks to my existing function.
Can someone help me out.
You can do it with strpos:
function satisfied($str, $k) {
return strpos($str, str_repeat('0', $k+1)) === false
&& strpos($str, str_repeat('1', $k+1)) === false;
}
or you can use preg_match with a simple alternation:
function satisfied($str, $k) {
$k++;
$pattern = '~0{' . $k . '}|1{' . $k . '}~';
return !preg_match($pattern, $str);
}
Note that preg_match returns an integer (or false if a problem occurs), but since there is a negation operator, the returned value is casted to a boolean.
You can take the input as character array and Here's exactly what your looking for :
<?php
function printCharMostRepeated($str)
{
if (!empty($str))
{
$max = 0;
foreach (count_chars($str, 1) as $key => $val)
if ($max < $val) {
$max = $val;
$i = 0;
unset($letter);
$letter[$i++] = chr($key);
} else if ($max == $val)
$letter[$i++] = chr($key);
if (count($letter) === 1)
echo 'The character the most repeated is "'.$letter[0].'"';
else if (count($letter) > 1) {
echo 'The characters the most repeated are : ';
$count = count($letter);
foreach ($letter as $key => $value) {
echo '"'.$value.'"';
echo ($key === $count - 1) ? '.': ', ';
}
}
} else
echo 'value passed to '.__FUNCTION__.' can\'t be empty';
}
$str = 'ddaabbccccsdfefffffqqqqqqdddaaa';
printCharMostRepeated($str);

How to get the count of string 2 occurrence in string 1 without php built-in functions

How to get the count of string 2 occurrence in string 1 without php built-in functions.
Example:
$strone = "Arun sukumar";
$strtwo = "a";
//Expected Output: 2
$strone = "Arun sukumar";
$strtwo = "uk";
//Expected Output: 1
I need to get the count without using any php built-in functions.
This is the question asked in a interview, is there any logic in that?
You need to take your needle, get the first char.. then iterate over each char of the haystack until you get match. Then take the next char of needle and check the next char of the haystack for a match... continue until you have the complete match for needle or until you fial to match a char.
hint: you can access the individual chars of a string by index with $string{0} where 0 is the zero based index of the char in the string.
$strone = 'arun sukumar';
$strtwo = 'a';
echo parsestr($strone, $strtwo);
function parsestr($strone, $strtwo)
{
$len = 0;
while ($strtwo{$len} != '') {
$len++;
}
$nr = 0;
while ($strone{$nr} != '')
{
if($strone{$nr} != ' ')
{
$data[$nr] = $strone{$nr};
}
$nr++;
}
$newdata = $data;
if($len > 1)
{
$newdata = array();
$j = 0;
foreach($data as $val)
{
$str .= $val;
if($j == ($len -1))
{
$newdata[] = $str;
$str = '';
$j = 0;
}
else
$j++;
}
}
$i = 0;
foreach($newdata as $val)
{
if($val == $strtwo)
{
$i++;
}
}
return $i;
}
Try this
$string = 'Arun sukumar';
$sub_string = 'a';
$count = 0;
for($i=0;$i < strlen($string); $i++){
$flag = 0;
$j=0;
if(strtolower($string[$i]) == $sub_string[$j])
{
//echo "match";
$flag = 1;
$k = $i;
for(;$j< strlen($sub_string); $j++){//echo "[".$j . $k."] $count $flag";
if(strtolower($string[$k]) != $sub_string[$j]){
$flag = 0;
break;
}
$k++;
}//echo "<br> $flag";
}
if($flag == 1){
$count++;
$flag = 0;
}
}
echo $count;
?>
Not sure why you would not want to use the built-in PHP functions since they would be faster, but something like this would work:
<?php
$haystack = 'Arun sukumar';
$needle = 'a';
// you seem to want a case insensitive search, so do a strtolower first
$haystack = strtolower($haystack);
$hitCount = 0;
for ($i = 0; $i < strlen($haystack); ++$i) {
if ($needle === substr($haystack, $i, strlen($needle))) {
$hitCount++;
}
}
echo 'Output: ' . $hitCount;
?>

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

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;

Categories