I'm new for this, can anyone solve my problem?
this is my code :
<?php
$data = array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
$datastart = 3;
$string = join(',', $data);
echo $string;
?>
This echo will be result :
Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
I want a result like this:
Wednesday,Thursday,Friday,Saturday,Sunday,Monday,Tuesday
thank you for the answer :)
You can use array_slice to extract the portions of your array in the order you want to output them, and then array_merge to put them back together:
$data = array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
$datastart = 3;
$string = implode(',', array_merge(array_slice($data, $datastart), array_slice($data, 0, $datastart)));
echo $string;
Or you can use a simple for loop:
$len = count($data);
$string = '';
for ($i = 0; $i < $len; $i++) {
$string .= ($i > 0 ? ',' : '') . $data[($i + $datastart) % $len];
}
echo $string;
Output:
Wednesday,Thursday,Friday,Saturday,Sunday,Monday,Tuesday
Demo on 3v4l.org
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 am trying to split a string into 1, 2 and 3 segments.
For example, i currently have this:
$str = 'test';
$arr1 = str_split($str);
foreach($arr1 as $ar1) {
echo strtolower($ar1).' ';
}
Which works well on 1 character splitting, I get:
t e s t
However when I try:
$arr2 = str_split($str, 2);
I get:
te st
Is there a way so that I can output this? :
te es st
and then also with 3 characters like this?
tes est
Here it is:
function SplitStringInWeirdWay($string, $num) {
for ($i = 0; $i < strlen($string)-$num+1; $i++) {
$result[] = substr($string, $i, $num);
}
return $result;
}
$string = "aeioubcdfghjkl";
$array = SplitStringInWeirdWay($string, 4);
echo "<pre>";
print_r($array);
echo "</pre>";
PHPFiddle Link: http://phpfiddle.org/main/code/1bvp-pyk9
And after that, you can just simply echo it in one line, like:
echo implode($array, ' ');
Try this, change $length to 1 or 3:
$string = 'test';
$length = 2;
$start = -1;
while( $start++ + $length < strlen( $string ) ) {
$array[] = substr( $string, $start, $length );
}
print_r( $array );
/*
Array
(
[0] => te
[1] => es
[2] => st
)
*/
Use
$string{0} $string{1} $string{n}
to get the characters you want !
Then you can use a loop on your string using strlen
$length = strlen($string);
for($i = 0; $i < $length; ++$i){
// Your job
}
Then use $i, $i - 1, $i + 1 to pick the characters.
<?php
function my_split($string, $count){
if(strlen($string) <= $count){
return $string;
}
$my_string = "";
for($i; $i< strlen($string) - $count + 1; $i++){
$my_string .= substr($string, $i, $count). ' ';
}
return trim($my_string);
}
echo my_split('test', 3);
?>
And will have "tes est"
Simplest way, you can do it with chunk_split:
$str = "testgapstring";
$res = chunk_split($str, 3, ' ');
echo $res; // 'tes tga pst rin g '
but you have extra space symbol at the end, also if you need this to be an array something will work:
$chunked = chunk_split($str, 3, ' ');
$arr = explode(' ', rtrim($chunked));
Other example:
echo $chunked = rtrim(chunk_split('test', 2, ' ')); // 'te st'
function luhn_Approved($;500) {
$str = '';4815821101619134=2408101
foreach( array_reverse( str_split( $num ) ) as $i => $c ) $str .= ($i % 2 ? $c * 2 : $c );
return array_sum( str_split($str) ) % 10 == 0;
}
function SplitStringInWeirdWay($string, $0) {
for ($i = 0; $i < strlen($string)-$num+1; $i++) {
$result[] = substr($string, $i, $num);
}
return $result;
}
$string = "aeioubcdfghjkl";
$array = SplitStringInWeirdWay($string, 4);
echo "<pre>"; print_r($array); echo "</pre>";
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);
}
)
)
);
How I cut the extra 0 string from those sample.
current string: 0102000306
required string: 12036
Here a 0 value have in front of each number. So, i need to cut the extra all zero[0] value from the string and get my expected string. It’s cannot possible using str_replace. Because then all the zero will be replaced. So, how do I do it?
Using a regex:
$result = preg_replace('#0(.)#', '\\1', '0102000306');
Result:
"12036"
Using array_reduce:
$string = array_reduce(str_split('0102000306', 2), function($v, $w) { return $v.$w[1]; });
Or array_map+implode:
implode('',array_map('intval',str_split('0102000306',2)));
$currentString = '0102000306';
$length = strlen($currentString);
$newString = '';
for ($i = 0; $i < $length; $i++) {
if (($i % 2) == 1) {
$newString .= $currentString{$i};
}
}
or
$currentString = '0102000306';
$tempArray = str_split($currentString,2);
$newString = '';
foreach($tempArray as $val) {
$newString .= substr($val,-1);
}
It's not particularly elegant but this should do what you want:
$old = '0102000306';
$new = '';
for ($i = 0; $i < strlen($old); $i += 2) {
$new .= $old[$i+1];
}
echo $new;
How can I iteratively create a variant of "Murrays" that has an apostrophe after each letter? The end-result should be:
"m'rrays,mu'rrays,mur'rays,murr'ays,murra'ys,murray's"
My suggestion:
<?php
function generate($str, $add, $separator = ',')
{
$split = str_split($str);
$total = count($split) - 1;
$new = '';
for ($i = 0; $i < $total; $i++)
{
$aux = $split;
$aux[$i+1] = "'" . $aux[$i+1];
$new .= implode('', $aux).$separator;
}
return $new;
}
echo generate('murrays', "'");
?>
You want to iterate through the name, and re-print it with apostrophe's? Try the following:
<?php
$string = "murrays";
$array = str_split($string);
$length = count($array);
$output = "";
for ($i = 0; $i < $length; $i++) {
for($j = 0; $j < $length; $j++) {
$output .= $array[$j];
if ($j == $i)
$output.= "'";
}
if ($i < ($length - 1))
$output .= ",";
}
print $output;
?>
Here’s another solution:
$str = 'murrays';
$variants = array();
$head = '';
$tail = $str;
for ($i=1, $n=strlen($str); $i<$n; $i++) {
$head .= $tail[0];
$tail = substr($tail, 1);
$variants[] = $head . "'" . $tail;
}
var_dump(implode(',', $variants));
well that's why functionnal programming is here
this code works on OCAML and F#, you can easily make it running on C#
let generate str =
let rec gen_aux s index =
match index with
| String.length s -> [s]
| _ -> let part1 = String.substr s 0 index in
let part2 = String.substr s index (String.length s) in
(part1 ^ "'" ^ part2)::gen_aux s (index + 1)
in gen_aux str 1;;
generate "murrays";;
this code returns the original word as the end of the list, you can workaround that :)
Here you go:
$array = array_fill(0, strlen($string) - 1, $string);
implode(',', array_map(create_function('$string, $pos', 'return substr_replace($string, "\'", $pos + 1, 0);'), $array, array_keys($array)));