For Loop Keep the variable - php

I'm trying to keep the for loop variable but I don´t know how,
This is the code that I use to make a string like: 1,2,3,4,5,6,7,8,9,10 ect.
for($i = 0; $i <= 17; $i++) {
$str = $i . ',';
}
Than:
$str = substr($str, 0, -1);
To get rid of the last char.
However, when I call the $str variable out of the for loop, it only outputs 17
Here is the whole code:
for($i = 0; $i <= 17; $i++)
{
$str = $i . ',';
}
$str = substr($str, 0, -1);
echo $str;
So to sum it up, I need the output to be 1,2,3,4,5,6,7,8,9,10 without a , at the end...

for($i = 0; $i <= 17; $i++)
{
// here
$str .= $i . ',';
}
$str = substr($str, 0, -1);
echo $str;
But there is a better way:
echo implode(',', range(0, 17));

Related

Browse a string with its own php function, accent problem [duplicate]

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;

get a set of values from an array

i have a set of arrays:
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
what i want to do is to get a set of $data array from each number of $nums array,
the output must be:
output:
2=11,22
3=33,44,55
1=66
what i tried so far is to slice the array and remove the sliced values from an array but i didn't get the correct output.
for ($i=0; $i < count($nums); $i++) {
$a = array_slice($data,0,$nums[$i]);
for ($x=0; $x < $nums[$i]; $x++) {
unset($data[0]);
}
}
Another alternative is to use another flavor array_splice, it basically takes the array based on the offset that you inputted. It already takes care of the unsetting part since it already removes the portion that you selected.
$out = array();
foreach ($nums as $n) {
$remove = array_splice($data, 0, $n);
$out[] = $remove;
echo $n . '=' . implode(',', $remove), "\n";
}
// since nums has 2, 3, 1, what it does is, each iteration, take 2, take 3, take 1
Sample Output
Also you could do an alternative and have no function usage at all. You'd need another loop though, just save / record the last index so that you know where to start the next num extraction:
$last = 0; // recorder
$cnt = count($data);
for ($i = 0; $i < count($nums); $i++) {
$n = $nums[$i];
echo $n . '=';
for ($h = 0; $h < $n; $h++) {
echo $data[$last] . ', ';
$last++;
}
echo "\n";
}
You can array_shift to remove the first element.
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
foreach( $nums as $num ){
$t = array();
for ( $x = $num; $x>0; $x-- ) $t[] = array_shift($data);
echo $num . " = " . implode(",",$t) . "<br />";
}
This will result to:
2 = 11,22
3 = 33,44,55
1 = 66
This is the easiest and the simplest way,
<?php
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
$startingPoint = 0;
echo "output:"."\n";
foreach($nums as $num){
$sliced_array = array_slice($data, $startingPoint, $num);
$startingPoint = $num;
echo $num."=".implode(",", $sliced_array)."\n";
}
?>

How to replace multiple random characters in string with underscore(_) in PHP

I am using codes like "gjhyYhK", "HJjhkeuJ" etc. But want user to show these codes like:
gj_y__K
HJj__e_J
means code will be edited with "_" at random positions in code.
This will do what you want:
$str = "gjhyYhK";
$len = strlen($str);
$num_to_remove = ceil($len * .4); // 40% removal
for($i = 0; $i < $num_to_remove; $i++)
{
$k = 0;
do
{
$k = rand(1, $len);
} while($str[$k-1] == "_");
$str[$k-1] = "_";
}
print $str . "\n";
If you want more underscores, change the value of $underscores. This will guarantee you get how many underscores you want, so long as you want fewer than the length of the string
Try this:
$string=array(
'gjhyYhK',
'HJjhkeuJ'
);
$arr=array();
foreach ($string as $key=>$value) {
$arr[$key]='';
for ($i=1; $i <=strlen($value); $i++) {
if(rand(0,1)){
$arr[$key].=substr($string[$key],$i,1);
}else{
$arr[$key].='_';
}
}
}
var_dump($arr);
you can try below code to get the functionality what you are looking for
<?php
$string = "gjhyYhK";
$percentage = 40;
$total_length = strlen($string);
$number_of_underscore = floor(($percentage / 100) * $total_length); // I have use floor value, you can use ceil() as well
for ($i = 1; $i <= $number_of_underscore; $i++)
{
$random_position = rand(0, strlen($string) - 1); // get the random position of character to be replaced
if (substr($string, $random_position, 1) !== '_') // check if its already replaced underscore (_)
{
$string = preg_replace("/" . (substr($string, $random_position, 1)) . "/", '_', $string, 1); // here preg_replaced use to replace the character only once, (i.e str_replace() will replace all matching characters)
}
else
{
$i--; // else decrement $i for the loop to run one more time
}
}
echo $string;
?>
let me know if any other help needed
$str = "ADFJ";
$strlen = strlen($str);
$newStr = '';
for ($i = 0; $i < $strlen; $i++) {
if ($i == rand(0, $strlen)) {
$newStr .= '_';
} else {
$newStr .= $str[$i];
}
}
echo $newStr;

Alphanumeric string increment using for loop

I have a two variable one is string contains number and another one is number,
I want increase the numeric part of string upto second number.
$n ='sh500';
$c = 3;
for($i=$n;$i<$c;$i++)
echo $i.'<br>';
I want output like:
sh500
sh501
sh502
Use $n++ where $n = 'sh500'. It works.
$n ='sh500';
$c = 3;
for($i = 0;$i < $c;$i++) {
echo $n++.'<br>';
}
Will output
sh500 <br>
sh501 <br>
sh502 <br>
It even works when ending with a alphanumeric character, because php converts it to the ASCII value of the character and adds one so a will become b and so on. But that's out of the scope of the question :)
$x="sh500";
$x = substr($x,0,2) . (substr($x,2) + 1);
echo $x;
echoes sh501 (works for any string having a number from 3rd character)
$n = 'sh';
for($i = 500; $i < 503; $i++) {
echo "$n$i\n";
}
$n="sh50";
for($i=0;$i<10;$i++){
$j=$n.$i;
echo $j."<br>";
}
it echo:
sh500
sh501
sh502
sh503
sh504
sh505
sh506
sh507
sh508
sh509
$n = 'sh500';
$c = 3;
$sh = substr($n,0,2); // will be "sh"
$number = substr($n,2,5) + 1; // will be "500"
for($i = $number; $i < 504; $i++) {
echo $sh.$i."\n";
}
Live demo: Here
if it is always a string of length 2 else use preg_match to find the first occurrence of a number.
http://www.php.net/manual/en/function.preg-match.php
$number = intval(substr($n, 2));
$number++;
echo substr($n, 0, 2) . $number;
$x = "sh500";
$s = substr($x, 0, 2);
$n = substr($x, 2);
$c = 3;
for ($i = $n; $i < ($n + $c); $i++)
{
echo $s.$i.'<br>';
}
OR another simple way is...
$n ='sh500';
$c = 3;
for ($i = 0; $i < $c; $i++) {
echo $n++."<br>";
}
Output
sh500
sh501
sh502

Generate string with apostrophe after each letter of original string in turn

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

Categories