I am trying to iterate a string containing cyrillic characters and perform concatenation, but my code is returning mangled text.
Here's the code:
$str = "слово";
$temp = "";
for ($i = 0; $i < strlen($str); $i++) {
$temp.=$str[$i];
echo $temp . '<br>';
}
echo $temp;
Output:
�<br>с<br>с�<br>сл<br>сл�<br>сло<br>сло�<br>слов<br>слов�<br>слово<br>слово
Desired Output:
с<br>сл<br>сло<br>слов<br>слово<br>слово
I've also tried to use mb_strlen() instead of strlen() but this didn't work either.
You cannot simply use offset numbers to access multibyte characters.
You need to use mb_strlen() AND mb_substr() to isolate your desired substrings.
*note: caching $len is a good idea. mb_ functions are expensive; it is best to minimize the number of times you call them in a script.
Code: (Demo)
$str = "слово";
$temp = "";
for ($i = 0, $len = mb_strlen($str); $i < $len; $i++) {
$temp .= mb_substr($str, $i, 1);
echo $temp . '<br>';
}
echo $temp;
Output:
с<br>сл<br>сло<br>слов<br>слово<br>слово
Depending on what your actual project needs are, here is an alternative that doesn't require a $temp variable:
$str = "слово";
for ($i = 0, $len = mb_strlen($str); $i < $len; $i++) {
if ($i) echo '<br>';
echo mb_substr($str, 0, $i + 1);
}
// с<br>сл<br>сло<br>слов<br>слово
More simply, you can split the string into an array of individual letters and iterate that. Demo
$str = "слово";
$temp = "";
foreach (mb_str_split($str) as $char) {
$temp .= $char;
echo $temp . '<br>';
}
echo $temp;
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;
}
}
I want to print integer in triangle form which look like this
1
121
12321
I tried this but I do not get the actual result
for($i=1;$i<=3;$i++)
{
for($j=3;$j>=$i;$j--)
{
echo " ";
}
for($k=1;$k<=$i;$k++)
{
echo $k;
}
if($i>1)
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Output of this code is:
1
1221
123321
Where am I going wrong, please guide me.
Another integer solution:
$n = 9;
print str_pad ("✭",$n," ",STR_PAD_LEFT) . PHP_EOL;
for ($i=0; $i<$n; $i++){
print str_pad ("", $n - $i);
for ($ii=-$i; $ii<=$i; $ii++){
if ($i % 2 != 0 && $ii % 2 == 0)
print "&#" . rand(10025,10059) . ";";
else print $i - abs($ii) + 1;
}
print PHP_EOL;
}
✭
1
1✬1
12321
1❊3✪3✳1
123454321
1✼3✶5❃5❈3✸1
1234567654321
1✾3✯5✿7❉7✫5✷3✶1
12345678987654321
Or if you already have the string, you could do:
$n = 9; $s = "12345678987654321"; $i = 1;
while ($i <= $n)
echo str_pad ("", $n-$i) . substr ($s,0,$i - 1) . substr ($s,-$i++) . PHP_EOL;
Your code should be this:
for($i=1;$i<=3;$i++)
{
for($j=3;$j>$i;$j--)
{
echo " ";
}
for($k=1;$k<$i;$k++) /** removed = sign*/
{
echo $k;
}
if($i>=1) /**added = sign*/
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Try this.
Details:
Your loop is not proper as in case of for($k=1;$k<=$i;$k++), this will print the
repeated number when check the condition for less then and again for equals to.
So remove the equals sign.
reason to add the eqaul sign in if($i>=1) is that the first element will not print if there will not be equals as first it will be print by for loop from where removed the equal sign.
Your output will be this:
1
121
12321
For all the x-mas lovers:
$max = 9; # can be 2 .. 9
for($i = 1; $i <= $max; $i++) {
$line = (str_pad('', $max - $i));
for($ii = 1; $ii <= $i; $ii++) {
$line .= $ii;
}
for($ii = $i-1; $ii > 0; $ii--) {
$line .= $ii;
}
echo $line . PHP_EOL;
}
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
Amazing what computers are able to achieve nowadays! Isn't it?
A little late to the party, but here's yet another solution that uses a "for" loop with two initialization variables and a ternary-based incrementer/decrementer. It's an unorthodox use of a "for" loop, but it's still perfectly valid and arguably makes the code more elegant and easier to follow. I chose to add space before and after each semicolon and omit all other space inside the parentheses so it's easier to visualize each of the three pieces of the "for" loop (initialization, condition, increment/decrement):
$count = 9;
echo "<pre>";
for ($i=1; $i<=$count; $i++) {
echo str_pad("",$count-$i," ",STR_PAD_LEFT);
for ( $j=1,$up=true ; $j>0 ; $up?$j++:$j-- ) {
echo $j;
if ($j==$i) {$up = false;}
}
echo "<br>";
}
echo "</pre>";
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
I use \b to generate backspace in PHP: But I think it doesn't work:
if(isset($_GET['submit'])){
$n = $_GET['n'];
$c = $_GET['c'];
$space = " "; $i=0; $j=0; $k=0;
do{
$space = $space." ";
$i++;
}while($i < $n);
for($j=0; $j < $n ; $j++){
echo $space;
for($k=0; $k < $j*2 - 1; $k++){
echo $c;
}
echo $space."\b";
echo "<br />";
}
}
If you want to delete last char in a string just do:
$space = substr($space,0,-1); //> Reccomanded
or
substr($space,0,count($space)-1); //> Slower
or
substr_replace($space,'',-1); //> Uglier
Maybe you mean this: "\x8" ?
Indeed, it's not on the list. You have to use the octal or hexadecimal notation.
In any case, the backspace character has little use outside a text console, not to mention HTML.
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;