equivalent syntax for 'for loop' & 'while loop'? - php

I know basic examples about foreach to for loop and while loop since I was begin coding I didn't paying attention from the speed of executing a script which it is very very important since then I keep converting all my for each statement to for loop. If it's comes to array i'm quite confused -_-. I know it gives me down vote posting this. LIKE I'd rather let people figure things out for myself.
I just need a bit of guide using a for loop statement. How can I convert the following foreach loop to for loop/ while loop statement?
like what I seen on phpbenchmark.com as
$i = 0; while($i < 1000000) ++$i;
for($i = 0; $i < 1000000; ++$i);
CODE:
<?php
$user['001'] = 'A';
$user['002'] = 'B';
$user['003'] = 'C';
$user['004'] = 'D';
foreach($user as $id => $name)
{
echo '<br>Id='.$id.'Name='.$name;
}
?>
thanks alot.
EXPECTED OUTPUT LIKE foreach output:
Id=001Name=A
Id=002Name=B
Id=003Name=C
Id=004Name=D
also what if I have an array keys like
$user['AAA'] = 'A';
$user['BBB'] = 'B';
$user['CCC'] = 'C';
$user['DDD'] = 'D';
it will output as:
Id=AAAName=A
Id=AAAName=B
Id=AAAName=C
Id=AAAName=D

The for and while loops you show are simply incrementing a number, which you can use to access elements of an array if the keys of that array are equivalent to those numbers. In other words, for or while loops have nothing to do with arrays as such, you're just using a number as a key to an array.
If your array keys are not simple continuous integers, this is more problematic. You could try to construct the correct keys from your $i variable, but why? You should just iterate explicitly over the keys of the array, for which foreach is perfect. You can also do it with each or any number of other complicated ways:
while (list($key, $value) = each($array)) {
...
}
But I doubt it's going to be significantly faster than a foreach.

Something like this...
<?php
$user['001'] = 'A';
$user['002'] = 'B';
$user['003'] = 'C';
$user['004'] = 'D';
while (current($user)) {
echo '<br>Id='.key($user).'Name='.$user[key($user)];
next($user);
}

try this
$user['001'] = 'A';
$user['002'] = 'B';
$user['003'] = 'C';
$user['004'] = 'D';
$keys = array_keys($user);
$length = sizeof($user);
for($i=0; $i<$length; $i++) {
echo 'id: '.$keys[$i].' value: '.$user[$keys[$i]].'<br />';
}

do you wanted something like this?
$length = count($user);
for ($i = 0; $i < $length; $i++) {
print $user[$i];
}
EDIT: or something like this?
$user = array ( '001' => 'A',
'002' => 'B',
'033' => 'C' );
while( list ( $id, $name) = each ( $user) )
{
echo '<br>Id=' .$id. 'Name='.$name;
}
EDIT:also works with you r AAA = A etc case

Related

PHP, array count, two foreach combination

I am solving this not understandable script, I even don't know where from to start. Maybe someone will help me.
I got two arrays example:
$a1 = array(1,2,3 ...);
$a2 = array(4,5,6 ...);
what I need is that first array will divide all values by itsel
for this I would like to get script which will work like this (array values can be savet to the same name because will be anyway continue with them, can be new variable, in this example I use new). In the same way variable can be devidet by itself to get 1 but prefer not to. Example of count.
$b1 = array([0]/[1], [0]/[2], [0]/[3], [1]/[0], [1]/[2], [1]/[3], [2]/[0], [2]/[1], [2]/[3], [3]/[0], [3]/[1], [3]/[2]);
$b2 = array( *** The same like $b1 ***);
On the end will go foreach to write values to table, this I solved already
echo "<table><tr>";
foreach($b1 as $key1 => $val1){
foreach($b2 as $key2 =>$val2){
echo "<td>".$key1.$key2."<br/>".val1*val2."</td>";
}
echo "</tr><tr>";
}
echo "</tr></table>"
Anyone can give me a help to this issue?
To do the division of each element is relatively simple. You do it with 2 for loops. The one thing you have to bear in mind, however, is avoiding division by 0. Do you have elements that could be 0? If so, do you want the division result to be 0, or the same as the numerator? the code I show below assumes the latter:
function getDivided($array) {
$length = count($array);
$return = [];
for ($i = 0; $i < $length; $i++) {
for ($j = 0; $j < $length; $j++) {
if ($i === $j) continue;
//the following assumes that the values in the array are never < 1 Change this according to your needs
$return[] = $array[$i] / max($array[$j], 1);
//Another option is to use a conditional
$return[] = $array[$j] === 0 ? $array[$i] : $array[$i] / $array[$j];
}
}
return $return;
}
$b1 = getDivided($a1);
$b2 = getDivided($a2);

Foreach into PHP array

I've this these array values :
$cart_item['addons'][0]['price'] = '52';
$cart_item['addons'][1]['price'] = '34';
$cart_item['addons'][2]['price'] = '12';
......
....
I want that each values are at 0 like :
$cart_item['addons'][0]['price'] = '0';
$cart_item['addons'][1]['price'] = '0';
$cart_item['addons'][2]['price'] = '0';
....
...
So I try this code :
for ($i=0; $i > 0 ; $i++) {
$cart_item['addons'][$i]['price'] = '0';
}
But it does not work. Thanks for your help !
Try this simple solution:
$count=count($cart_item['addons']);
for($i=0; $i<$count;$i++ ){
$cart_item['addons'][$i]['price'] = '0';
}
If your array is big enough, putting count() function inside for loop is being a crazy coconut. It will be much, much slower. Please use the count outside the loop:
$count = count($cart_item['addons'])
for($i=0; $i<$count;$i++ ){
$cart_item['addons'][$i]['price'] = '0';
}
You have to loop more often to achive this:
foreach($cart_item['addons'] as &$addons {
foreach($addons as &$addon) {
$addon['price'] = 0;
}
}
You can iterate over $cart_item['addons'], like so:
foreach ($cart_item['addons'] AS $key => &$value) {
$value['price'] = 0;
}
(Your code does not get executed, because $i is never changed and so is never > 0)
Also note that you need to use the reference (&$value) when changing the array in foreach loop.
There are three parts to your for loop: for(counter | test | action){}. It might be useful for you to look at this guide about for loops. You initialise your variable:
$i = 0;
then you do a logical check (the test part):
$i > 0;
If we substitute the the variable ($i) for the value it holds (0) we get:
0 > 0
which will never be true and thus you will never get to the final part (action) of the for loop:
$i++;
Instead you could make it loop until it has moved through your entire array like this:
$elementCount = count(cart_item['addons']);
for($i=0; $i < $elementCount; $i++){
$cart_item['addons'][$i]['price'] = '0';
}
Each time it loops we add one to $i until we reach the stopping condition where $i is no longer less than the number of items in the array.
It's also worth noting that PHP has a number of functions that help working with arrays.

Using an index twice in PHP

I am trying to use a for loop where it looks through an array and tries to make sure the same element is not used twice. For example, if $r or the random variable is assigned the number "3", my final array list will find the value associated with wordList[3] and add it. When the loop runs again, I don't want $r to use 3 again. Example output: 122234, where I would want something along the lines of 132456. Thanks in advance for the help.
for($i = 0; $i < $numWords; $i++){
$r = rand(0, $numWords);
$arrayTrack[$i] == $r;
$wordList[$r] = $finalArray[$i];
for($j = 0; $j <= $i; $j++){
if($arrayTrack[$j] == $r){
# Not sure what to do here. If $r is 9 once, I do not want it to be 9 again.
# I wrote this so that $r will never repeat itself
break;
}
}
Edited for clarity.
Pretty sure you are over complicating things. Try this, using array_rand():
$final_array = array();
$rand_keys = array_rand($wordList, $numWords);
foreach ($rand_keys as $key) {
$final_array[] = $wordList[$key];
}
If $numWords is 9, this will give you 9 random, unique elements from $wordList.
See demo
$range = range(0, $numWords - 1); // may be without -1, it depends..
shuffle($range);
for($i = 0; $i < $numWords; $i++) {
$r = array_pop($range);
$wordList[$r] = $finalArray[$i];
}
I do not know why you want it.. may be it is easier to shuffle($finalArray);??
So ideally "abcdefghi" in some random order.
$letters = str_split('abcdefghi');
shuffle($letters);
var_dump($letters);
ps: if you have hardcoded array $wordList and you want to take first $n elements of it and shuffle then (if this is not an associative array and you do not care about the keys)
$newArray = array_slice($wordList, 0, $n);
shuffle($newArray);
var_dump($newArray);
You can try array_rand and unset
For example:
$array = array('one','two','free','four','five');
$count = count($array);
for($i=0;$i<$count;$i++)
{
$b = array_rand($array);
echo $array[$b].'<br />';
unset($array[$b]);
}
after you have brought the data in the array, you purify and simultaneously removing the memory array
Ok... I have NO idea why you are trying to use so many variables with this.
I certainly, have no clue what you were using $arrayTrack for.
There is a very good chance I am mis-understanding all of this though.
<?php
$numWords=10;
$wordList=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$finalArray=array();
for ($i=0; $i<$numWords; $i++) {
start:
$r=rand(0,$numWords);
$wordChoice=$wordList[$r];
foreach ($finalArray as $word) {
if ($word==$wordChoice) goto start;
}
$finalArray[]=$wordChoice;
}
echo "Result: ".implode(',',$finalArray)."\n";

How to call variables sharing the same name but ending with different numbers by assigning a variable to these numbers

I couldn't find a better title for this problem. I have variables like this: $var1, $var2, $var3.
In a for loop, I want to display these variables:
for ( $j = 1; $j <= 3; $j++ ) {
echo $var$j;
}
Of course this won't work, but what is the syntax to do it? If $var1 = 1, $var2 = 2 and $var3 = 3, I want this result: "123".
Use curly braced syntax (known as variable variables):
for ( $j = 1; $j <= 3; $j++ ) {
echo ${"var$j"};
}
Also, as #Alnitak mentioned in comment:
if you're using numbers to handle a set of variables like this, you should have used an array in the first place.
So array is definately an option, as it might be exact case for it's usage.
This is how to solve your problem:
How to put a value inside :
// $content is an array of values.
for ( $j = 1; $j <= 3; $j++ ) {
$var_name = "var".$j;
$$var_name = $content[$j];
}
And how to read them :
for ( $j = 1; $j <= 3; $j++ ) {
$var_name = "var".$j;
echo $$var_name;
}
But may I suggest to use arrays:
// $content is an array of values.
foreach ( $content as $key=>$value) {
echo $content[$key];
echo $value; //same as previous line
unset($content[$key]);//to remove a value from an array
}
If you can, switch to using arrays instead of these variables. If you can't, you can still use an array:
foreach (array($var1, $var2, $var3) as $current) {
echo $current;
}
I think one should use an Array instead of lots of unnecessary variables.
Keeping things structured, as what is held here is a Data Structure at all.
One may implode/join them using an empty value as is:
$values = [1,2,3];
echo join('', $values);
As simple as that! Think of it!
By the sake of portability, there may be the case where an Associative Array is used, let's say when the data is fetched from a Database Rowset.
As of PHP has a way to extract array values only, one can use:
$values = [
'value1' => 1,
'value2' => 2,
'value3' => 3
];
echo join('', array_values($values));
And, finally, considering the previous associative concept, it is also possible to use object properties:
$obj = new \stdClass();
$obj->value1 = 1;
$obj->value2 = 2;
$obj->value3 = 3;
echo join('', array_values(get_object_vars($obj)));
This will work for you:
$var1 = "1";
$var2= "2";
$var3 = "3";
for ( $j = 1; $j <= 3; $j++ ) {
echo ${"var".$j};
}
and the output will be
123
The syntax is
${"firstPart".$lastPart};
which is equal to
$firstPartlastPart
You may read about it more here: http://www.php.net/manual/en/language.variables.variable.php

foreach php statement

I need to combine two foreach statement into one for example
foreach ($categories_stack as $category)
foreach ($page_name as $value)
I need to add these into the same foreach statement
Is this possible if so how?
(I am not sure I have understood your question completely. I am assuming that you want to iterate through the two lists in parallel)
You can do it using for loop as follows :
$n = min(count($category), count($value));
for($c = 0; $c < $n; $c = $c + 1){
$categories_stack = $category[$c];
$pagename = $value[$c];
...
}
To achieve the same with foreach you need a function similar to Python's zip() function.
In Python, it would be :
for categories_stack, pagename in zip(categories, values):
print categories_stack, pagename
Since PHP doesn't have a standard zip() function, you'll have to write such a function on your own or go with the for loop solution.
You can do nested foreachs if that's what you want. But without knowing more of your data, it's impossible to say if this helps:
foreach ($categories_stack as $category) {
foreach ($page_name as $value) {
}
}
Probably you want to print out all pages in a category? That probably won't work, so can you give a bit more info on how the arrays look like and relate to each other?
This loop will continue to the length of the longest array and return null for where there are no matching elements in either of the arrays. Try it out!
$a = array(1 => "a",25 => "b", 10 => "c",99=>"d");
$b = array(15=>1,5=>2,6=>3);
$ao = new ArrayObject($a);
$bo = new ArrayObject($b);
$ai = $ao->getIterator();
$bi = $bo->getIterator();
for (
$ai->rewind(),$bi->rewind(),$av = $ai->current(),$bv = $bi->current();
list($av,$bv) =
array(
($ai->valid() ? $ai->current() : null),
($bi->valid() ? $bi->current() : null)
),
($ai->valid() || $bi->valid());
($ai->valid() ? $ai->next() : null),($bi->valid() ? $bi->next() : null))
{
echo "\$av = $av\n";
echo "\$bv = $bv\n";
}
I cannot really tell from the question exactly how you want to traverse the two arrays. For a nested foreach you simply write
foreach ($myArray as $k => $v) {
foreach ($mySecondArray as $kb => $vb {
}
}
However you can do all sorts of things with some creative use of callback functions. In this case an anonymous function returning two items from each array on each iteration. It's then easy to use the iteration value as an array or split it into variables using list() as done below.
This also has the added benefit of working regardless of key structure. I's purely based on the ordering of array elements. Just use the appropriate sorting function if the elements are out of order.
It does not worry about the length of the arrays as there is no error reported, so make sure you keep an eye out for empty values.
$a = array("a","b","c");
$b = array(1,2,3);
foreach (
array_map(
create_function(
'$a,$b', 'return array($a,$b);'
)
,$a,$b
)
as $value
)
{
list($a,$b) = $value;
echo "\$a = $a\n";
echo "\$b = $b\n";
}
Output
$a = a
$b = 1
$a = b
$b = 2
$a = c
$b = 3
Here's another one for you that stops on either of the lists ending. Same as using min(count(a),count(b). Useful if you have arrays of same length. If someone can make it continue to the max(count(a),count(b)) let me know.
$ao = new ArrayObject($a);
$bo = new ArrayObject($b);
$ai = $ao->getIterator();
$bi = $bo->getIterator();
for (
$ai->rewind(),$bi->rewind();
$av = $ai->current(),$bv=$bi->current();
$ai->next(),$bi->next())
{
echo "\$av = $av\n";
echo "\$bv = $bv\n";
}
This is where the venerable for loop comes in handy:
for(
$i = 0,
$n = sizeof($categories_stack),
$m = sizeof($page_name);
$i < $n && $i < $m;
$i++
) {
$category = $categories_stack[$i];
$value = $page_name[$i];
// do stuff here ....
}
Surely you can just merge the arrays before looping?
$data = array_merge($categories_stack, $page_name);
foreach($data AS $item){
...
}
Do the array elements have a direct correspondence with one another, i.e. is there an element in $page_name for each element in $categories_stack? If so, just iterate over the keys and values (assuming they have the same keys):
foreach ($categories_stack as $key => $value)
{
$category = $value;
$page = $page_name[$key];
// ...
}
Could you just nest them with variables outside the scope of the foreach, or prehaps store the content as an array similar to a KVP setup? My answer is vague but I'm not really sure why you're trying to accomplish this.

Categories