for loop with if statement - array without comma - php

This is my part of code:
for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ )
{
$aData = $this->aProducts[$aProducts[$i]];
$content .= '"'.$aData['sName'].'"';
if ($i < $aKeys['iEnd'])
{
$content .= ', ';
}
$i2++;
}
Full code gives me this as result:
["word1", "word2", "word3", ]
This is a simple array, which I will use, but this won't work because after word3 there is a comma sign. How to write this if statement to get result like: ["word1", "word2", "word3"] ?

Put a condition on the length-1 to fix your bug.
for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ ){
$aData = $this->aProducts[$aProducts[$i]];
$content .= '"'.$aData['sName'].'"';
if ($i < $aKeys['iEnd']-1) {
$content .= ', ';
}
$i2++;
}

Alternatively you can use an array for this. And at the end simply implode them.
for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ ){
$aData = $this->aProducts[$aProducts[$i]];
$content[] = '"'.$aData['sName'].'"';
}
$content = '"' . implode('","', $content) . '"';

You can use rtrim() to remove comma.
rtrim($content, ',');
As I can see you want all names as comma separated. Than you can do like that as well :
$content = array();
for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ ){
$aData = $this->aProducts[$aProducts[$i]];
$content[] = $aData['sName'];
}
echo implode(',',$content);

for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ ){
$aData = $this->aProducts[$aProducts[$i]];
$content .= '"'.$aData['sName'].'"';
if ($i < $aKeys['iEnd'] && $i!=($aKeys['iEnd']-1)) { //this condition also considers $i not to be the last element of the array before appending the comma to it.
$content .= ', ';
}
$i2++;
}

Use array_push(); function
$var = array();
loop(condition){
array_push($var, $value);
}

Related

Convert simple string to Required Format : PHP

I would like to Convert simple string to set based on below logic
if string is 3,4-8-7,5 then I need the set as (3,8,7),(4,8,5).
The Logic behind to building the set are we need to consider ',' as OR condition and '-' as AND condition.
I am trying my best using For loop :
$intermediate = array();
$arry_A = explode('-', '3,4-8-7,5');
for ($i = 0; $i < count($arry_A); $i++) {
$arry_B = explode(',', $arry_A[$i]);
for ($j = 0; $j < count($arry_B); $j++) {
if (count($intermediate) > 0) {
for ($k = 0; $k < count($intermediate); $k++) {
$intermediate[$k] = $intermediate[$k] . ',' . $arry_B[$j];
}
} elseif (count($intermediate) === 0) {
$intermediate[0] = $arry_B[$j];
}
}
}
echo $intermediate, should give final result.
This Code works correctly, Try this
<?php
$intermediate = array();
$str="";
$val='3,4-8-7,5';
$vals=str_replace(',','-',$val);
$j=1;
$arry_A = explode('-',$vals );
$str.='(';
for ($i = 0; $i < count($arry_A); $i++) {
if($j==3){
$str.=$arry_A[$i].',';
$str.='),';
$str.='(';
$j=1;
}
else
$str.=$arry_A[$i].',';
$j++;
}
echo substr($str, 0, -2);
?>

PHP fill array into for

in this below code i want to fill array with for repeator. echo can display and not have problem but. my array could not fill by for.
<meta charset='UTF-8' />
<?php
error_reporting(1);
$handle='A-file.txt';
$handle = file_get_contents($handle);
$lines = explode(PHP_EOL,$handle );
$names = array();
for( $i = 0; count($lines)-1 ; $i+=4 )
{
$names[]= $lines[$i];
//$names= $lines[$i];
//$names[]+= $lines[$i];
//echo $lines[$i];
}
print_r($names);
?>
You've forgotten the comparison with $i:
for( $i = 0; $i <= count($lines)-1 ; $i+=4 )
{
$names[]= $lines[$i];
//$names= $lines[$i];
//$names[]+= $lines[$i];
//echo $lines[$i];
}
Try this, You have missed to add $i < count($lines)-1
for( $i = 0; $i < count($lines)-1; $i+=4 )
instead of
for( $i = 0; count($lines)-1 ; $i+=4 )
Check the file has more than 4 lines, and the for finishes with that condition maybe will be an eternal loop.
This is perhaps just a tip to solve the problem more likely.
Use file() (http://php.net/file) to directly read a file's content into an array (so you don't need to do it manually with more lines then needed) and iterate over these lines using foreach($lines as $i => $line) {...} instead. To skip lines you can do:
if($i % $nthElem !== 0) continue;
You could even do it in one turn:
foreach(file($yourFile) as $i => $line){
if($i % 4 !== 0) continue;
Always optimize your for loop by putting count function out of for loop and store it in a variable. Use that in the loop
$count = count($lines);
for( $i = 0; $count-1 ; $i+=4 ) {
}

Finding string position with for loop

For a school project I need to find the position of the string "AAAAAA" in a long string. I need to use a for loop. So far I came up with the following code:
<?php
$string1 = "TATAGTTTCCTCTCTATAT";
$string2 = str_repeat("AAAGCCTCAAATCTCTCTAGTAAAAAAGCCTCAAATCTCTCTAGTAAA", 6);
$count = strlen($string1.=$string2);
for($i = 0; $i < $count; $i++){
$string_to_find = $count{$i};
print(strpos($string_to_find, 'AAAAAA'));
}
?>
I can't get it to work. What am I doing wrong?
If you are using strpos(), you dont required to use for loop. you can get the results without that.
<?php
$string1 = "TATAGTTTCCTCTCTATAT";
$string_to_find="";
$string2 = str_repeat("AAAGCCTCAAATCTCTCTAGTAAAAAAGCCTCAAATCTCTCTAGTAAA", 6);
$count = strlen($string1.=$string2);
for($i = 0; $i < $count; $i++){
$string_to_find.=$string1{$i};
print(strpos($string_to_find, 'AAAAAA'));
}
?>
here is the code you can try.
I think doing it with a for/foreach loop is really bad,
anyway, here is your code, changed your code a little, hope it works
<?php
$string1 = "TATAGTTTCCTCTCTATAT";
$string2 = str_repeat( "AAAGCCTCAAATCTCTCTAGTAAAAAAGCCTCAAATCTCTCTAGTAAA", 6 );
$count = strlen( $string1 .= $string2 );
$temp = null;
foreach( str_split( $string1 ) as $char ) {
$temp .= $char;
if ( ( $pos = strpos( $temp, "AAAAAA" ) ) !== false ) {
print( $pos." " );
$temp = null;
}
}
?>

PHP: Display comma after each element except the last. Using 'for' statement and no 'implode/explode'

I have this simple for loop to echo an array:
for ($i = 0; $i < count($director); $i++) {
echo ''.$director[$i]["name"].'';
}
The problem here is that when more than one element is in the array then I get everything echoed without any space between. I want to separate each element with a comma except the last one.
I can't use implode so I'm looking for another solution
This should work. It's better I think to call count() once rather than on every loop iteration.
$count = count($director);
for ($i = 0; $i < $count; $i++) {
echo ''.$director[$i]["name"].'';
if ($i < ($count - 1)) {
echo ', ';
}
}
If I remember PHP syntax correctly, this might also help:
$str = "";
for ($i = 0; $i < count($director); $i++) {
$str .= ''.$director[$i]["name"].', ';
}
$str = trim($str, ", ");
A better solution is to avoid looping altogether. I've ignored building the links for the sake of clarity. Note that I don't believe the inability to use implode is a condition. I believe it's a simple statement of, "I can't see how to make this work using implode, so I did it this way instead."
$last_entry = array_pop($director);
if(count($director) > 0) {
echo implode(", ", $director) . " and " . $last_entry;
} else {
echo $last_entry;
}
My preferred method:
$links = [];
for ($i = 0; $i < count($director); $i++) {
$links[] = '<a href="person.php?id='.$director[$i]["id"].'">' .
$director[$i]["name"] . '</a>';
}
echo implode(', ', $links);
Or
$output = "";
for ($i = 0; $i < count($director); $i++) {
if ($output) {
$output .= ", ";
}
$output .= '<a href="person.php?id='.$director[$i]["id"].'">' .
$director[$i]["name"].'</a>';
}
echo $output;
for ( $i=0 ; $i < count($arr)-1 ; $i++ )
{
echo ( $arr[$i]."," );
}
echo ( $arr[count($arr)-1] );
$number = count($director);
for ($i = 0; $i < $number; $i++) {
echo ''.$director[$i]["name"].'';
if($i < $number - 1){
echo ', ';
}
}
Oops, I didn't saw the reply by Tom Haigh, we came with practically the same.
How about something like this? You may want to store the result of "count($director)" in a variable outside the loop so that you do not have to waste resources recalculating it each time the loop is run.
for($i=0; $i<count($director);$i++){
echo ''.$director[$i]["name"].'';
if($i!=count($director)-1){echo ',';}
}
Well, foreach contains for :-)
foreach ($director as $key => $person) {
if ($key !== 0) echo ', ';
echo ''.$person['name'].'';
}
// RENAMED $director to $directors
$links = '';
foreach ($directors AS $director) {
$links .= "{$director['name']}";
if (true !== empty($links)) {
$links .= ', ';
}
}
echo $links;
foreach ($strings as $string){
$superstring .= $string . ', ';
}
$echostring = substr_replace($superstring ,"",-2);
echo $echostring;
Here's my 2 lines solution
// Create your Array
$cities = Array("Rome", "Florence", "Venice");
// implode them
$list = trim(implode (", ", $cities)) ;
// remove last comma
$list = substr ( $list,0 ,strlen( $list ) );
//check result
die ($list);
$count =1;
for ($i = 0; $i < count($director); $i++) {
if ($count!=1) {
echo ' , ';
}
echo ''.$director[$i]["name"].'';
$count++;
}

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