I am trying to find a way to reverse a string, I've seen alternatives but i wanted to to it this way thinking outside the box and not using anyone else's code as an alternative, the code below reverses the string but I keep getting this error:
Notice: Undefined offset: 25 in C:\wamp\www\test\index.php on line 15
25 being the length of the string which is being deincremented.
//error_reporting(NULL);
$string = trim("This is a reversed string");
//find length of string including whitespace
$len =strlen($string);
//slipt sting into an array
$stringExp = str_split($string);
//deincriment string and echo out in reverse
for ($i = $len; $i >=0;$i--)
{
echo $stringExp[$i];
}
thanks in advance
You're trying much too hard, always consult the manual and/or a search engine to check if there are native functions to do what you want before you end up "reinventing the wheel":
strrev — Reverse a string
http://php.net/manual/en/function.strrev.php
$string = "This is a reversed string";
echo strrev($string);
// Output: gnirts desrever a si sihT
As others said, there's strrev() to do this.
If you want to build it on your own (for learning?): your problem is that you're starting with your index one too high - a string of length 25 is indexed from 0 to 24, so your loop has to look like this:
for ($i = $len - 1; $i >=0;$i--)
{
echo $stringExp[$i];
}
$string = 'mystring';
$length = strlen($string);
for ($i = $length; $i > 0; $i--){
echo $string[$i-1];
}
OUTPUT: gnirtsym
You must get $len-1 because string starts from 0 to $len-1
There is a function for this strrev
echo strrev("This is a reversed string!");
php is quite complete in term of string function you just need to pass the string . thats why php is easy :)
use strrev php function http://bg2.php.net/manual/en/function.strrev.php
<?php
echo strrev("This is a reversed string");
?>
// Output: gnirts desrever a si sihT
<?php
// Reversed string and Number
// For Example :
$str = "hello world. This is john duvey";
$number = 123456789;
$newStr = strrev($str);
$newBum = strrev($number);
echo $newStr;
echo "<br />";
echo $newBum;
OUTPUT :
first : yevud nhoj si sihT .dlrow olleh
second: 987654321
for ($i = $len-1; $i >=0;$i--)
{
echo $stringExp[$i];
}
Since the index starts at 0
Change your for loop to
for ($i = $len-1; $i >=0;$i--)
{
echo $stringExp[$i];
}
<?php
echo strrev("PHP TUTORS");
?>
OUTPUT OF THE ABOVE SCRIPT
SROTUT PHP
Reference Source Code
You can use it:
echo $reversed_s = join(' ',array_reverse(explode(' ',"Hello World")));
public function stringReverse($string="Jai mata di")
{
$length = strlen($string) - 1;
$i = 0;
while ($i < $length + 1) {
echo $string[$length - $i];
$i++;
}
}
We can do String Reverse with help of following menthods
$string = "Hello world!";
1st way to do:
echo strrev($string);
2nd way to do:
$stringSplit = str_split($string);
for ($i = $len-1; $i >=0;$i--)
{
echo $stringSplit[$i];
}
This will work
class StringUtils {
public function stringReverse($string){
$arr1 = str_split($string);
$arr2 = array();
for($i = count($arr1); $i >= 0; $i--){
$arr2[count($arr1) - $i] = $arr1[$i];
}
return implode("", $arr2);
}
}
<?php
/* Reverse a string with php */
echo strrev("Hello World!");
?>
Reverse a string php
Related
This question already has answers here:
Reverse the letters in each word of a string
(6 answers)
Closed 1 year ago.
This is the code I have so far. I just started learning PHP today and I'm not sure why my code isn't working.
<?php
function backwards($input)
{
$str = $input;
$revStr = "";
$str = explode(",",$str);
for($x = 0; $x < strlen($str); $x++){
$revStr .= strrev($str[$x]);
}
return $revStr;
}
Any help would be greatly appreciated!
edit: Here is an example input
Php,Arrays,Mysql
here is what i would like the output to be:
phP,syarrA,lqsyM
edit2:
Figured it out. Made a few minor edits. Not sure if it's the most efficient code but it works.
<?php
function backwards($input)
{
$str = $input;
$revStr = "";
$str = explode(",",$str);
for($x = 0; $x < count($str); $x++){
if($x == count($str) - 1){
$revStr .= strrev($str[$x]);
}
else{
$revStr .= strrev($str[$x]) . ",";
}
}
return $revStr;
}
Edit, I see you now included an example.
Use array_map and strrev to reverse the words.
Use explode and Implode to make the words array and back to string.
echo implode(",", array_map(function($part){ return strrev($part);},explode(",", $str)));
https://3v4l.org/tr7d6
I believe you should use array_reverse on the exploded string.
Then you can implode it back to a string.
$str = "apple,orange,tomato";
$arr = explode(",", $str);
$arr =array_reverse($arr);
echo implode(",", $arr); //tomato,orange,apple
https://3v4l.org/Hvd9m
Or, slightly messier but compact:
echo implode(",", array_reverse(explode(",", $str)));
https://3v4l.org/LTu90
You are checking the string length of an array inside of your for loop. Also, a custom function is unnecessary, PHP provides us with strrev().
But if you would like to use your own:
function backwards($input)
{
$str = $input;
$revStr = "";
$str = explode(",",$str);
for($x = 0; $x < count($str); $x++){
$revStr .= strrev($str[$x]);
}
return $revStr;
}
$string = "Php,Arrays,Mysql";
echo backwards($string);
Hope this helps,
You need to use count instead of strlen and also need to take reversed string into array and then convert it into string.
You can try this code :
<?php
function backwards($input)
{
$str = $input;
$revStr = array();
$str = explode(",", $str);
for ($x = 0; $x < count($str); $x++) {
$revStr[] = strrev($str[$x]);
}
return implode(',', $revStr);
}
$str = "Php,Arrays,Mysql";
var_dump(backwards($str));
Just some modification and you got your desired output. You can use explode and implode function of php with array_push to get your result:
<?php
$string = "Php,Arrays,Mysql";
function backwards($input)
{
$str = $input;
$revStr = array();
$str = explode(",", $str);
for ($x = 0; $x < count($str); $x++) {
array_push($revStr, strrev($str[$x]));
}
return implode(',', $revStr);
}
$result =backwards($string);
echo $result;
?>
You can check the demo here
use $str[0] in for loop syntax.
like this => for($x = 0; $x < strlen($str[0]); $x++)
I don't really know how to go about but it really pretty for me in achievement like each rand_string to each index.
My code:
function rand_string($length) {
$str="";
$chars = "abcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0; $i < $length; $i++) {
$str .= $chars[rand(0, $size-1)];
}
return $str;
}
$pcode = rand_string(4);
for ($b = 0; $b < 3; $b++) {
echo $pcode[$b];
}
I am expecting something like: 9cwm cZnu c9e4 in the output. Can I achieve this in PHP?
Currently, with my code, I get a string from rand_string in each index like 9cw.
Your code works, you only need to call rand_string inside your second loop in order to get something like 9cwm cZnu c9e4 (what you have described in your question).
Here is a working example:
function rand_string($length) {
$str="";
$chars = "abcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0;$i < $length;$i++) {
$str .= $chars[rand(0,$size-1)];
}
return $str;
}
// call rand_string inside for loop
for ($b = 0; $b<3; $b++) {
echo rand_string(4).' ';
}
Try it online
The generation of the string actually works in your code. You aren't calling/printing the function correctly. Just call the function three times and print all the results (with spaces in between). Instead of printing you could join it together in a string and remove the last space.
<?php
function rand_string($length) {
$str="";
$chars = "abcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0;$i < $length;$i++) {
$str .= $chars[rand(0,$size-1)];
}
return $str;
}
for ($b = 0; $b<3; $b++)
{
echo rand_string(4)." ";
}
If you don't mind using a completely different approach, limited to 32 chars :
return substr(md5(mt_rand().time()), 0, $length);
It's not super random but you get the picture...
Thanks to CM and user2693053 for bringing stuff to my attention (updated answer)
using mt_rand() instead of rand()
md5() length of 32...
Some time ago during a job interview I got the task to reverse a string in PHP without using strrev.
My first solution was something like this:
$s = 'abcdefg';
$temp = '';
for ($i = 0, $length = mb_strlen($s); $i < $length; $i++) {
$temp .= $s{$length - $i - 1};
}
var_dump($temp);
// outputs string(7) "gfedcba"
then they asked me if I could do this without doubling the memory usage (not using the $temp variable or any variable to copy the reversed string to) and I failed.
This kept bugging me and since then I tried to solve this multiple times but I constantly failed.
My latest try looks like this:
$s = 'abcdefg';
for ($i = 0, $length = mb_strlen($s); $i < $length; $i++) {
$s = $s{$i * 2} . $s;
}
var_dump($s);
// outputs string(14) "gfedcbaabcdefg"
It's not a solution to chop off "abcdefg" after the loop because then I would still double the amount of memory used. I need to remove the last character in every iteration of the loop.
I tried to use mb_substr like this:
$s = 'abcdefg';
for ($i = 0, $length = mb_strlen($s); $i < $length; $i++) {
$s = $s{$i * 2} . mb_substr($s, $length - $i - 1, 1);
}
var_dump($s);
but it only gives me Uninitialized string offset errors.
This is where I'm stuck (again). I tried googling but all the solutions I found either echo the characters directly or use a temporary variable.
I also found the Question PHP String reversal without using extra memory but there's no answer that fits my needs.
That's an interesting one.
Here's something I just came up with:
$s = 'abcdefghijklm';
for($i=strlen($s)-1, $j=0; $j<$i; $i--, $j++) {
list($s[$j], $s[$i]) = array($s[$i], $s[$j]);
}
echo $s;
list() can be used to assign a list of variables in one operation. So what I am doing is simply swapping characters (starting with first and last, then second-first and second-last and so on, till it reaches the middle of the string)
Output is mlkjihgfedcba.
Not using any other variables than $s and the counters, so I hope that fits your criteria.
You can use the fact that in PHP a string can be thought of as an array of characters.
Then basically what you want to do is to replace each character $i on the left side of the middle of the string with the character $j on the right side of the middle with the same distance.
For example, in a string of seven characters the middle character is on position 3. The character on position 0 (distance 3) needs to be swapped with the character on position 6 (3 + 3), the character on position 1 (distance 2) needs to be swapped with the character on position 5 (3 + 2), etc.
This algorithm can be implemented as follows:
$s = 'abcdefg';
$length = strlen($s);
for ($i = 0, $j = $length-1; $i < ($length / 2); $i++, $j--) {
$t = $s[$i];
$s[$i] = $s[$j];
$s[$j] = $t;
}
var_dump($s);
$string = 'abc';
$reverted = implode(array_reverse(str_split($string)));
You could use the XOR swap trick.
function rev($str) {
$len = strlen($str);
for($i = 0; $i < floor($len / 2); ++$i) {
$str[$i] = $str[$i] ^ $str[$len - $i - 1];
$str[$len - $i - 1] = $str[$i] ^ $str[$len - $i - 1];
$str[$i] = $str[$i] ^ $str[$len - $i - 1];
}
return $str;
}
print rev("example");
Try this:
$s = 'abcdefg';
for ($i = strlen($s)-1; $i>=0; $i--) {
$s .= $s[$i];
$s[$i] = NULL;
}
var_dump(trim($s));
Here it is PHP7 version of this:
echo "\u{202E}abcdefg"; // outs: gfedcba
PHP strings are kinda-sorta mutable, but due to copy-on-write it's very difficult to modify them in-place without a copy being made. Some of the above solutions work, but only because they're stand-alone; some already fail because they define a function without a pass-by-reference argument. To get the code to actually operate in-place in a larger program, you'd need to pay careful attention to assignments, function arguments, and scopes.
Example:
$string1 = 'abc';
$string2 = $string1;
$string1[0] = 'b';
print("$string1, $string2");
> "abc, bbc"
I suppose that if between initializing the variable and modifying it you only ever used by-reference assignments (&=) and reference arguments (function rev(&$string)) (or assign the string to an object property initially, and then never assign it to any other variable), you might be able to change the original value of the string without making any copies. That's a bit ridiculous, however, and I'd assume that the interviewer who came up with that question didn't know about copy-on-write.
This isn't quite the same as immutability in other languages, by the way, because it applies to arrays too:
$a = [0, 1, 2];
$b = $a;
$b[0] = 1;
print(implode($a).implode($b));
> "012112"
To sum up, all types (except for objects as of PHP5) are assigned with copy-on-write unless you specifically use the &= operator. The assignment doesn't copy them, but unlike most other languages (C, Java, Python...) that either change the original value (arrays) or don't allow write access at all (strings), PHP will silently create a copy before making any changes.
Of course, if you switched to a language with more conventional pointers and also switched to byte arrays instead of strings, you could use XOR to swap each pair of characters in place:
for i = 0 ... string.length / 2:
string[i] ^= string[string.length-1-i]
string[string.length-1-i] ^= string[i]
string[i] ^= string[string.length-1-i]
Basically #EricBouwers answer, but you can remove the 2nd placeholder variable $j
function strrev2($str)
{
$len = strlen($str);
for($i=0;$i<$len/2;$i++)
{
$tmp = $str[$i];
$str[$i] = $str[$len-$i-1];
$str[$len-$i-1] = $tmp;
}
return $str;
}
Test for the output:
echo strrev2("Hi there!"); // "!ereht iH"
echo PHP_EOL;
echo strrev2("Hello World!"); // "!dlroW olleH"
This will go through the list and stop halfway, it swaps the leftmost and rightmost, and works it's way inward, and stops at the middle. If odd numbered, the pivot digit is never swapped with itself, and if even, it swaps the middle two and stops. The only extra memory used is $len for convenience and $tmp for swapping.
If you want a function that doesn't return a new copy of the string, but just edits the old one in place you can use the following:
function strrev3(&$str)
{
$len = strlen($str);
for($i=0;$i<$len/2;$i++)
{
$tmp = $str[$i];
$str[$i] = $str[$len-$i-1];
$str[$len-$i-1] = $tmp;
}
}
$x = "Test String";
echo $x; // "Test String"
strrev3($x);
echo PHP_EOL;
echo $x; // "gnirtS tseT"
Using &$str passes a direct pointer the the string for editing in place.
And for a simpler implementation like #treegardens, you can rewrite as:
$s = 'abcdefghijklm';
$len = strlen($s);
for($i=0; $i < $len/2; $i++) {
list($s[$i], $s[$len-$i-1]) = array($s[$len-$i-1], $s[$i]);
}
echo $s;
It has the similar logic, but I simplified the for-loop quite a bit.
Its Too Simple
//Reverse a String
$string = 'Basant Kumar';
$length = strlen($string);
for($i=$length-1;$i >=0;$i--){
echo $string[$i];
}
Here is my code to solve your problem
<?php
$s = 'abcdefg';
for ($i = 0, $length = mb_strlen($s); $i < $length; $i++) {
$s = $s{$i}.mb_substr($s,0,$i).mb_substr($s,$i+1);
}
var_dump($s);
?>
You could also use a recursion to reverse the string. Something like this for example:
function reverse($s) {
if(strlen($s) === 1) return $s;
return substr($s, strlen($s)-1) . reverse(substr($s , 0, strlen($s)-1));
}
What you do here is actually returning the last character of the string and then calling again the same function with the substring that contains the initial string without the last character. When you reach the point when your string is just one character then you end the recursion.
You can use this code to reverse a string without using the reserved function in php.
Code:
<?php
function str_rev($y)// function for reversing a string by passing parameters
{
for ($x = strlen($y)-1; $x>=0; $x--) {
$y .= $y[$x];
$y[$x] = NULL;
}
echo $y;
}
str_rev("I am a student");
?>
Output:
tneduts a ma I
In the above code, we have passed the value of the string as the parameter.We have performed the string reversal using for loop.
you could use substr with negative start.
Theory & Explanation
you can start with for loop with counter from 1 to length of string, and call substr inside iteration with counter * -1 (which will convert the counter into negative value) and length of 1.
So for the first time counter would be 1 and by multiplying with -1 will turn it to -1
Hence substr('abcdefg', -1, 1); will get you g
and next iteration substr('abcdefg', -2, 1); will get you f
and substr('abcdefg', -3, 1); will get you e
and so on ...
Code
$str = 'abcdefghijklmnopqrstuvwxyz';
for($i=1; $i <= strlen($str); $i++) {
echo substr($str, $i*-1, 1);
}
In Action: https://eval.in/583208
public function checkString($str){
if(!empty($str)){
$i = 0;
$str_reverse = '';
while(isset($str[$i])){
$strArr[] = $str[$i];
$i++;
}
for($j = count($strArr); $j>= 0; $j--){
if(isset($strArr[$j])){
$str_reverse .= $strArr[$j];
}
}
if($str == $str_reverse){
echo 'It is a correct string';
}else{
echo 'Invalid string';
}
}
else{
echo 'string not found.';
}
}
//Reverse String word by word
$str = "Reverse string word by word";
$i = 0;
while ($d = $str[$i]) {
if($d == " ") {
$out = " ".$temp.$out;
$temp = "";
}
else
$temp .= $d;
$i++;
}
echo $temp.$out;
The following solution is very simple, but it does the job:
$string = 'Andreas';
$reversedString = '';
for($i = mb_strlen($string) - 1; $i >= 0; $i--){
$reversedString .= $string[$i];
}
var_dump($reversedString) then results: string(7) "saerdnA"
<?php
$value = 'abcdefg';
$length_value = strlen($value);
for($i = $length_value-1; $i >=0 ;$i--){
echo $value[$i];
}
?>
you can try this..
$string = "NASEEM";
$total_word = strlen($string);
for($i=0; $i<=$total_word; $i++)
{
echo substr($string,$total_word-$i,1);
}
i have used some built in function but without str_rev function .
<?php
$text = "red";
$arr = str_split($text);
$rev_text = array_reverse($arr);
echo join(" ",$rev_text);
?>
Try This
<?php
$str="abcde";
for($i=strlen($str)-1;$i>=0;$i--){
echo $str[$i];
}
?>
output
edcba
This is my solution to solve this.
$in = 'This is a test text';
$out = '';
// find string length
$len = strlen($in);
// loop through it and print it reverse
for ( $i = $len - 1; $i >=0;$i-- )
{
$out = $out.$in[$i];
}
echo $out;
Reverse string using recursion function.
$reverseString = '';
function Reverse($str, $len)
{
if ($len == 0) {
return $GLOBALS['reverseString'];
} else {
$len--;
$GLOBALS['reverseString'] .= $str[$len];
return Reverse($str, $len);
}
}
$str = 'Demo text';
$len = strlen($str);
echo Reverse($str, $len)
Try this
$warn = 'this is a test';
$i=0;
while(#$warn[$i]){
$i++;}
while($i>0)
{
echo $warn[$i-1]; $i--;
}
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;
How can I achieve number 4,7,8 separately if there is a given variable: $i=478 such that I can store $j=4,$k=7,$l=8 in PHP. Is there a function?
$i = 478;
$stri = (string)$i;
$j = $stri[0];
$k = $stri[1];
$l = $stri[2];
You should cast the number to a string and then str_split it:
$numbers = str_split((string)$number); // or
list($a, $b, $c) = str_split((string)$number); // but this might throw a notice if $number is 12 or 8 or something
Use type case and convert number to string
$i=478 ;
$i= (string)$i ;
String can be accessed as array hence you can do
echo $i[0]; //to access 4
you can iterate as array as well using loops
$len=strlen($i);
for($j=0; $j <= $len; $j++)
{
echo $i[$j]."<br>";
}
try
$n=567;
$x = (string)$n;
for($i=0;$i<strlen($x);$i++)
{
echo "<br/>".$x[$i];
}
UPDATE:
to find the average
for($i=0;$i<strlen($x);$i++)
{
echo "<br/>".$x{$i};
$t+=(int)$x[$i];
}
echo "average:". $t/strlen($x);