Reverse a string in php without using any string function - php

In yesterday Interview I was asked that how to reverse a string with out using any string function like strrev() or strlen(). I found this example on website but it gives error.is it possible to do this without strlen().
Uninitialized string offset: -1 in
D:\xampp\htdocs\PhpProject1\index.php on line xx
$string = "ZEESHAN";
$i =0;
while(($string[$i])!=null){
$i++;
}
$i--;
while(($string[$i])!=null){
echo $string[$i];
$i--;
}

$string = 'zeeshan';
$reverse = '';
$i = 0;
while(!empty($string[$i])){
$reverse = $string[$i].$reverse;
$i++;
}
echo $reverse;

Try -
$string = "ZEESHAN";
$j = 0;
while(!empty($string[$j])) {
$j++;
}
for($i = ($j-1); $i >= 0; $i--) {
echo $string[$i];
}
Output
NAHSEEZ

I have created a simple logic for string reversal
$str = 'ABCD';
$strReversed = '';
$length = strlen($str);
for($i=$length-1; $i >= 0; $i--){
$strReversed .= $str[$i];
}
echo $strReversed;

You can use while and for loop like as
$string = "ZEESHAN";
$reverse = "";
$j = 0;
while(isset($string[$j])){
$j++;
}
for($i = $j - 1; $i >= 0; $i--){
$reverse .= $string[$i];
}
echo $reverse;

You can try it with count_chars and array_sum
<?php
$string = "ZEESHAN";
$count=array_sum(count_chars($string));
for($i=$count -1 ;$i>=0;$i--){
echo $string[$i];
}
?>
If you dont want any php string function you can try this way with krsort and array:
<?php
$string = "ZEESHAN";
$arr = array();
$i=0;
while(isset($string[$i])){
$arr[$i] = $string[$i];
$i++;
}
krsort($arr);
$final = implode("",$arr);
var_dump($final);
?>

//Program for reversing a string
<?php
class str_rev{
public function Revese_Str($string){
$reverse = '';
$i=0;
while(!empty($string[$i])){
$reverse = $string[$i].$reverse;
$i++;
}
return $reverse;
}
}
$object = new str_rev();
echo $object->Revese_Str('Ayush Jain');

Check this code to resolve this problem.
<?php
$string = "ZEESHAN";
$i =0;
while(!empty($string[$i])){
$i++;
}
$i--;
while(!empty($string[$i])){
echo $string[$i];
$i--;
}
?>

You can do this
$string = "heya";
$i = strlen("heya") - 1;
$newStr = "";
while($i >= 0) {
$newStr .= $string[$i];
$i--;
}
echo $newStr; // output: ayeh

<!doctype html>
<html>
<body>
<center>
<form action="#" method="get">
<br>
<input type="text" name="txt"/>
<br><br>
<input type="submit" name="submit"/>
<br><br>
</form>
<?php
if(isset($_GET["submit"])) {
$name = $_GET["txt"];
for ($i = 0; isset($name[$i]); $i++) {
$j = $i;
}
for ($k = $j; isset($name[$k]); $k--) {
echo $name[$k];
}
}

Please take a look the below code: Reverse the string
$str = 'abcdefg';
$reverseString = '';
for($i=strlen($str);$i<=strlen($str);$i--){
$reverseString .= $str[$i];
if($i==0)
break;
}
echo $reverseString;
The above code output is:
gfedcba

<?php
$string = 'ZEESHAN';
$reverse = '';
$i = 0;
while(!empty($string[$i])){
$reverse = $string[$i].$reverse;
$i++;
}
echo $reverse;
?>
Check complete post: https://www.troposal.com/reverse-string-without-function-php/

Related

How to create a user defined function in PHP exactly the same as str_replace(), without using any other built-in functions except for strlen()

<?php
echo my_string_replace("world","jonathan","hello world helloworld");
function my_string_replace($find, $replace, $string)
{
//Block of codes here...
}
?>
I can only use loops, if else statements, and other commands such as break and continue. I want to create my own algorithm. Please help me. This should output : hello jonathan hellojonathan"
error_reporting(0); used for hide "Uninitialized string offset" notice.
<?php
function str_v2($num){
error_reporting(0);
for($i=0; $num[$i] != "";$i++);
echo $i; }//end of function
$name = "Hope this will work.";
echo str_v2($name);
?>
That was a fun brain teaser. Here you go:
echo my_string_replace("world", "jonathan", "hello world helloworld");
function my_string_replace($find, $replace, $string)
{
$characterCount = strlen($string);
$findCount = strlen($find);
$replaceCount = strlen($replace);
for ($i = 0; $i < $characterCount - $findCount +1; $i++) {
if ($string[$i] == $find[0]) {
$j = 1;
$found = true;
while ($j < $findCount) {
if ($string[$i + $j] != $find[$j]) {
$found = false;
break;
}
$j++;
}
if ($found) {
// copy string until current position
$replaced = '';
for ($x = 0; $x < $i; $x++) {
$replaced .= $string[$x];
}
// append replacement
$replaced .= $replace;
// copy after match till end
for ($x = $i + $findCount; $x < $characterCount; $x++) {
$replaced .= $string[$x];
}
// continue with replaced string, after replacement
$string = $replaced;
$characterCount = strlen($string);
$i = $i + $replaceCount;
}
}
}
return $string;
}

php code to reverse a string using paramaterized function

Below is my Code to Reverse a String..
The code runs well but I need to wrap this code inside Paramaterized function
in which user pass a string inside function and get return output.
<?php
$string = trim("This");
$len =strlen($string);
$stringExp = str_split($string);
for ($i = $len-1; $i >=0;$i--)
{
echo $stringExp[$i];
}
?>
for Ex -
I want above string reversal code logic like below function...
<?php
$str = "rahul";
echo reverse($str);
function reverse($str)
{
for ($i = 0, $j = strlen($str) - 1; $i < $j; $i++, $j--) {
$tmp = $str[$i];
$str[$i] = $str[$j];
$str[$j] = $tmp;
}
return $str;
}
?>
Simply try this
$str = "rahul";
echo reverse($str);
function reverse($str)
{
$tmp = '';
for($i = (strlen($str)-1);$i >= 0; $i--) {
$tmp .= $str[$i];
}
return $tmp;
}
There is strev() function which does it but if you need write your own here is the code
$str = "abcde";
function reverse ($str)
{
$output = '';
for ($i = strlen($str)-1; $i >= 0 ; --$i) {
$output .= $str[$i];
}
return $output;
}
echo reverse($str);

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

defining alphabets as numbers not working inside loop

Please check my code below,it returns 0 while I am expecting a result 14.But when I add A+D manually it returns 5.Am i doing something wrong inside the loop ?
<?php
define('A',1);
define('B',2);
define('C',3);
define('D',4);
define('E',5);
//echo A+D; returns 5
$name = 'EACE';
$len = strlen($name);
for($i = 0; $i<=$len; $i++)
{
$val += $name[$i];
}
echo $val; //returns 0
?>
You need to use constant(..) to get the value of a constant by name. Try this:
for ($i = 0; $i < strlen($name); $i++) {
$val += constant($name[$i]);
}
define('A',1);
define('B',2);
define('C',3);
define('D',4);
define('E',5);
//echo A+D; returns 5
$name = 'EACE';
$len = strlen($name);
$val = null;
for($i = 0; $i<=$len-1; $i++)
{
$val += constant($name[$i]);
}
echo $val;

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

Categories