Replacing "foreach" with "for" in PHP - php

I need to replace my "foreach" with "for", but actually I don't know how.
Here is the part of my php code:
$r = "";
$j = 0;
foreach ($orgs as $k => $v) {
echo "\n\r" . $v->id . "\n\r";
if (1) {
$a_view_modl = ArticleView :: model($v->id, $v->id);
$connection = $a_view_modl->getDbConnection();
Thanks!

$r = "";
$j = 0;
foreach ($orgs as $k => $v) {
echo "\n\r" . $v->id . "\n\r";
if (1) { //you don't really need this, because it's allways true
$a_view_modl = ArticleView :: model($v->id, $v->id);
$connection = $a_view_modl->getDbConnection();
if $orgs is an associative array, it becomes:
$r = "";
$j = 0;
for($i = 0; $i < count($orgs); $i++)
{
echo "\n\r" . $orgs[$i]->id . "\n\r";
$a_view_modl = ArticleView :: model($orgs[$i]->id, $orgs[$i]->id);
$connection = $a_view_modl->getDbConnection();
}
better you do some checks first if you go for this solution.
if you implement your solution with foreach which is in this case more readable, you can increment or decrement a given variable, like normal:
$i++; //if you want the increment afterwards
++$i; //if you want the increment before you read your variable
the same for decrements:
$i--; //decrement after reading the variable
--$i; //decrement before you read the variable

$r = "";
$j = 0;
for($i = 0 ; $i < count($orgs); $i++)
{
$v = $orgs[$i];
echo "\n\r" . $v->id . "\n\r";
if (1) {
$a_view_modl = ArticleView :: model($v->id, $v->id);
$connection = $a_view_modl->getDbConnection();
}

A foreach loop is just a better readable for loop. It accepts an array and stores the current key (which is in this case an index) into $k and the value into $v.
Then $v has the value you are using in the snippet of code.
A for loop does only accept indexed arrays, and no associative arrays.
We can rewrite the code by replacing $v with $orgs[ index ], where index starts from 0.
$r = "";
$j = 0;
for ($i = 0; $i < count($orgs); $i++) {
echo "\n\r" . $orgs[$i]->id . "\n\r";
if (1) {
$a_view_modl = ArticleView::model($orgs[$i]->id, $orgs[$i]->id);
$connection = $a_view_modl->getDbConnection();

foreach ($orgs as $k => $v) {
// Your stuff
}
for loop
for ($i = 0; $i < count($orgs); $i++) {
// Your stuff ... use $orgs[$i];
}

Related

Increment number by 1 in foreach loop upto 10

I am trying to increment a value in a foreach loop, but I need it to be maximum 10. How can I do that? My current code is
$i = 0;
foreach ( $signatures as $signature ) {
echo 'Signature ID: ' . $signature . $i;
$i++;
}
Where this foreach loop should stop when the value of $i should reach 10.
Thanks
This would do it.
$i = 0;
foreach ( $signatures as $signature ) {
if($i==10){
break;
}
echo 'Signature ID: ' . $signature . $i;
$i++;
}
Just use break if you want to end any iteration.
Along with breaking the foreach loop at 10, you could just do a for loop:
If $signatures is a numerical array:
for($i = 0; $i < 10; $i++) {
$signature = $signatures[$i];
}
If $signatures is an associative array, access with current() and advance with next():
for($i = 0; $i < 10; $i++) {
$signature = current($signatures);
next($signatures);
}

dynamic array variable with dynamic values

I am in too much trouble. I need below type of array:-
$val = "abc";
$arr1["besk"] = $val
$arr2["besk"] = $val
.
.
$arr15["besk"] = $val
I tried below:-
for($i = 1; $i<16; $i++)
{
$arr.$i["besk"] = $val
}
here I've $val. so not to worry on that. But array is not properly creating. Any help would be appreciated.
first define the array as string
like
$arr = 'arr';
then use the foreach
like
for($i = 1; $i<16; $i++)
{
${$arr.$i}["besk"] = $val;
}
You need to use variable variables (not recommended)
for($i = 1; $i<16; $i++)
{
${"arr".$i}["besk"] = $val
}
EDIT : #CBroe is right about his comment, you should use an array instead. So the best solution would be to create a two dimensional array like so :
$arr = [];
for($i = 0; $i<15; $i++)
{
$arr[$i]["besk"] = $val
}
The only difference is your array indexes start from 0 now and if you want to have the third value of your array you need this command $arr[2]["besk"]
it is very simple use this:
for($i = 1; $i<16; $i++)
{
${$arr.$i}["besk"] = $val
}
Use this approach:
for($i = 1; $i<16; $i++)
{
${$arr.$i}["besk"] = $val;
}
add new variable
$val = "abc";
$arrName = "arr"; //this one
$arr1["besk"] = $val
$arr2["besk"] = $val
.
.
$arr15["besk"] = $val
and to call it
for($i = 1; $i<16; $i++)
{
${$arrName.$i}["besk"] = $val
}
ps. you did not create array, you just create 15 array variable with 1 index("besk" index)

Issue splitting an array for use in another array

I have some data, which i currently have hard coded, basically i am trying to split the numbers, 1-port and recreate it as
'INSERT INTO '.$tbl_name.'(PortNumber) VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(145),(146),(147),(148),(149),(150),(151),(152),(153),(154),(155),(156)';
and etc.. i have a pretty good start i think..
PHP
//post vars
$port = 24; //(int)$_POST['ports'];
$super = 2; //(int)$_POST['super'];
$col = 12; //(int)$_POST['columns'];
$row = 2; //(int)$_POST['rows'];
//rest of vars
$halfPort=$port/2;//12
$colHalf = $col / $super;//6
$half=$colHalf-1;//5
$count=1;
$and=1;
$one=1;
echo "<h1>here goes nothen</h1><br><br>";
//sperate port
$finalArray = array();
for ($i = $port; $i >= 1; $i -= $colHalf) {
$tempArray = array();
for ($j = 0; $j < $colHalf; $j++) {
$tempArray[] = $i - $j;
}
$tempArray[]= sort($tempArray);
$finalArray[] = implode(",", $tempArray);
}
$finalArray = array_reverse($finalArray);
echo "<pre>" . print_r($finalArray, true) . "</pre>";
echo "<br><br>";
//sql for insert
$sqlinsert='
INSERT INTO '.$tbl_name2.'
(PortNumber) VALUES ';
$start='(';
$end=')';
//preset b
$b=0;
for($c = $port; $c >= 1; $c -= $colHalf) {
$queryStart = array();
$queryStart[]=explode(',',$finalArray[$b]);
echo "<pre>" ."start". print_r($queryStart, true) . "</pre>";
for($s=0; $s<6; $s+=$and) {
$queryEnd = array();
$queryEnd[] = $start.$queryStart[$s].$end;
echo "<pre>" ."end". print_r($queryEnd, true) . "</pre>";
}
$b+=1;
}
to view it live insert it here: http://phptester.net/index.php?lang=en
baisaclly it gets to $queryEnd, everything goes down hill, any ideas?
I'm not quite sure what you want to do, but if you just want to build something like the INSERT query you can do something like:
$tbl_name = '?';
echo 'INSERT INTO '.$tbl_name.'(PortNumber) VALUES ('.implode('),(', array_merge(range(1,12),range(145,156))).')';
I think I see it. You are reinitializing your $queryEnd array every time the For loop runs. Move that out of the For loop.
Mike

Variable PHP Variables

I am new to the concept of variable variables and don't think I fully understand it.
What I am trying to do is create a for loop that will populate an array based on a variable number of variables.
I am trying to replace: (manually hard coded)
$numCorrectArray = array(1=>$q01TotalCorrect, 2=>$q02TotalCorrect, 3=>$q03TotalCorrect, 4=>$q04TotalCorrect, 5=>$q05TotalCorrect, 6=>$q06TotalCorrect, 7=>$q07TotalCorrect, 8=>$q08TotalCorrect, 9=>$q09TotalCorrect, 10=>$q10TotalCorrect, 11=>$q11TotalCorrect, 12=>$q12TotalCorrect, 13=>$q13TotalCorrect, 14=>$q14TotalCorrect, 15=>$q15TotalCorrect, 16=>$q16TotalCorrect, 17=>$q17TotalCorrect, 18=>$q18TotalCorrect, 19=>$q19TotalCorrect, 20=>$q20TotalCorrect, 21=>$q21TotalCorrect, 22=>$q22TotalCorrect, 23=>$q23TotalCorrect, 24=>$q24TotalCorrect, 25=>$q25TotalCorrect, 26=>$q26TotalCorrect, 27=>$q27TotalCorrect, 28=>$q28TotalCorrect, 29=>$q29TotalCorrect);
With: (dynamic)
$numCorrectArray = array();
for($i=1; $i <= $stats->numberOfQuestions; $i++) {
if($i < 10) {
$questionNumber = "0" . $i;
} else {
$questionNumber = $i;
}
$varName = "q" . $questionNumber . "TotalCorrect";
array_push($numCorrectArray, $$varName);
}
How would I accomplish this? Thanks
The below method i think is easier to understand because is similar to normal PHP code. Here you can learn more.
$numCorrectArray = array();
$prefix = 'q';
$sufix = 'TotalCorrect';
for($i=1; $i <= 30; $i++) {
if($i < 10) {
$questionNumber = "0" . $i;
} else {
$questionNumber = $i;
}
${$prefix . $questionNumber . $sufix} = $i;
$numCorrectArray[$i] = ${$prefix . $questionNumber . $sufix};
}

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++;
}

Categories