Multiply in while() - php

I need to multiply variables, but the amount of them is not always the same, is there any function to do so, or how to solve this?
$string = "abc";
$amn = strlen($string);
$i = 1;
while ($i <= $amn) {
$comb[$i] = $i;
$i++;
}
It will save numbers 1, 2, and 3 into variable $comb[$i], and i need to multiply them between each other $comb[1]*$comb[2]*$comb[3]. Thank you in advance.

there is one function array_sum (http://php.net/manual/de/function.array-sum.php). This sums your array. If you need the product use array_product.
BR,
TJ

What about this:
$product = 1;
while($i <= $amn){
$product = $product*$i;
$i++;
}
This computes the factorial n!, which is 1*2*3*4*5*...*n (you can leave out the multiplication by one, because it is actually a nop).
You could also use a for loop, to make things more compact:
$product = 1;
for($i = 2; $i <= $amn; $product *= $i++);

first of all, since you're working with an index, running a loop a given ammount of time, a for loop is more sutable here, it manages the scoping of the index variable $i and makes for more readable code.
for($i=1;$i<=strlen($str);$i++){
$comb[$i]=$i;
}
now to multiply each of them:
$product = 1;
foreach($com as $key => $value){
$product*=$value;
}
If what you're trying to do is to just compute a factorial, you don't even need to make an array:
function factorial($num){
$fac = 1;
for($i=2;$i<=$num){
$fac*=$i;
}
}

Related

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

PHP Count 1 too many on Array as it's 0 based?

I've had this problem a few times now when for looping over an array item.
In this instance I'm generating all 2 letter combinations of the alphabet.
The code works (and I know there's a much easier way of doing it with 2 for loops, but I'm trying something different).
However I have to do count -1 as count() returns the number 26 for the array length, however the 26th item obviously doesn't exist as it's 0 based?
Is there not a version of count() that works on a zero-based basis?
<?php
$alphas = range('a', 'z');
$alphacount = count($alphas);
// Why do I have to do this bit here?
$alphaminus = $alphacount -1;
$a = 0;
for ($i=0;$i<$alphacount;$i++) {
$first = $alphas[$a];
$second = $alphas[$i];
if ($i === $alphaminus && $a < $alphaminus ) {
$i = 0;
$a ++;
}
echo "$first$second<br>";
}
?>
Without $alphaminus = $alphacount -1; I get undefined offset 26?
How about:
<?php
$alphas = range('a', 'z');
$alphacount = count($alphas);
$a = 0;
for ($i=0;$i<$alphacount;$i++) {
$first = $alphas[$a];
$second = $alphas[$i];
if ($i >= $alphacount && $a < $alphaminus ) {
$i = 0;
$a ++;
}
echo "$first$second<br>";
}
So you don't have to to -1 since you don't like it! :)
And how about:
$alphas = range('a', 'z');
for ($i = 0; $i < count($alphas); $i++) {
for ($a = 0; $a < count($alphas); $a++) {
echo "{$alphas[$i]}{$alphas[$a]}\n";
}
}
Or forget about arrays! This is more fun :)
array_walk($alphas, function ($a) use ($alphas) {
array_walk($alphas, function ($b) use ($a) {
print "$a$b\n";
});
});
The problem is that you reset $i to 0 in the loop; then on encountering the end of the loop $i is incremented, so the next run in the loop will be with $i = 1 instead of $i = 0.
That is, the next subrange of letters starts with (letter)b instead of (letter)a. (See your output: the next line after az is bb rather than ba.)
Solution: reset $i to -1 in the loop, then at the end it will run with the value 0 again.
You have 26 characters, but arrays in PHP are indexed from 0. So, indexes are 0, 1, ... 25.
count is 1-based and arrays created by range() are 0-based.
It means that:
$alphas[0] == a
$alphas[25] == z
$count($alphas) = 26; // there are 26 elements. First element is $alphas[0]
Why does it have to be so complicated? You could simply do
foreach ($alphas as $alpha)
{
foreach($alphas as $alpha2)
{
echo $alpha.$alpha2."<br>";
}
}
Note: It is mostly not a good idea to manipulate the loop counter variable inside the body of that very loop. You set $i to 0 on a certain condition. That could give you unexpected results, hence the reason why you have to navigate around it.

use variable name in code processing php like $number01 use it value, not name

so better will be example (so hard to give a title to this problem)
imagine I have variables in php like
$number1 = 10;
$number2 = 30;
$number3 = 23;
.. and so on..
and I just want to make an arithmetic average but not like
($number1 + $number2 +$number3)/3 because it is so much typing (having more than only 3 numbers)
but use something like
$temp=0;
for ($i=1;$i<50;$i++){
$temp=$temp+$number."$i"; <- this is what I don't know how to define..
}
and similar, how to echo all values for numbers like
for ($i=1;$i<50;$i++){
echo $number.$i; <- but this is not working..
}
I hope I have described it good, thank you for your help!
It can be done with variable variables but it's ugly:
$temp=0;
for ($i=1;$i<50;$i++){
$temp=$temp+(${$number.$i});
}
There is a limitation with the variable variables which is you don't know how high the number goes. You would also need to check if the variable is set first. A better solution is to store each of the variables in an array, which you can easily iterate over:
$arr = array();
$arr[] = 10;
$arr[] = 30;
$arr[] = 23;
$temp = 0;
foreach($arr as $val)
{
$temp += $val;
}
$number = array(10,20,30);
echo array_sum($number);
the other solution doing the same with for loop
$number = array(10,20,30);
$count = count($number);
$sum = 0;
for($i = 0; $i < $count ; ++$i) $sum += $number[$i];
or foreach
$number = array(10,20,30);
$count = count($number);
$sum = 0;
foreach($number as $n) $sum += $n;
there are a lot of methods to add items to array for example
$number = array(10,20,30);
$number = array();
$number[] = 10; $number[] = 20; $number[] = 30;
$number[0]= 10; $number[1] = 20; $number[2] = 30;
$number = array();
array_push($number, 10, 20, 30);
But the most simple and working solution is to use arrays and array_sum() function.
Array sum - Calculate the sum of values in an array
It's probably better to put all these values into an array instead of different variables. This makes adding later easier and allows you to loop like:
foreach($myArray as $number){
echo $number;
}
If you still want/need to use variables you can use variable variables:
$temp=0;
for ($i=1;$i<50;$i++){
$numberName = "number".$i;
$temp=$temp + $$numberName;//Note the $$ syntax.
}
$$foo will be the value of the variable with the name stored in $foo.
A final note. Be careful with variable variables, as they can lead to messy or unreadable code.
use an array
$number[0] = 10;
$number[1] = 20;
$number[2] = 23;
for ($i=1;$i<count($number);$i++) {
echo $number[$i]; //now this works.
}

How to sort it better?

I have 2 arrays, both are multidimensional with same number of elements and same values, which are on different positions (those values are actually ID-s from my database, so one ID appears only once). How can I sort second array with values which are in first array?
For example - if first array looks like:
$array1[0][0] = 1;
$array1[0][x] = it doesn't matter what's here
$array1[1][0] = 4;
$array1[1][x] = it doesn't matter what's here
$array1[2][0] = 3;
$array1[2][x] = it doesn't matter what's here
...
how to sort second array so it would have same values as array1 on indexes [0][0], [1][0], [2][0], etc.
How I could solve problem is:
$i=0
while ($i < (count($array1)-2)){ // * check down
$find_id = $array1[$i][0];
// here I need to search for index of that ID in other array
$position = give_index($find_id, $array2);
// swapping positions
$temp = array2[$i][0];
$array2[$i][0] = $array2[$position][0];
$array2[$position][0] = $temp;
// increasing counter
i++;
}
function give_index($needle, $haystack){
for ($j = 0, $l = count($haystack); $j < $l; ++$j) {
if (in_array($needle, $haystack[$j][0])) return $j;
}
return false;
}
*There is only -2 because indexes start from 0 and also for the last element you don't need to check since it would be automatically sorted by last iteration of while-loop.
I don't find this solution good as I think that this is quite simple issue (maybe it's not even correct). Is there easier way in PHP that I'm missing?
This is the most efficient way I can think of:
function swap(&$a, &$b) {
$t = $a;
$a = $b;
$b = $t;
}
function find_index($id, $array, $from = 0) {
$index = false;
for ($i = $from, $c = count($array); $i < $c; $i++) {
if ($array[$i][0] == $id) {
$index = $i;
break;
}
}
return $index;
}
for ($i = 0, $c = count($array1); $i < ($c - 2); $i++) {
if ($array1[$i][0] != $array2[$i][0]) {
$fi = find_index($array1[$i][0], $array2, $i);
swap($array2[$i][0], $array2[$fi][0]);
}
}
What changes from yours?
I've defined a swap() function in order to swap any variable. That doesn't cost anything and makes everything look nicer. Also you can reuse that function later if you need to.
In the find_index (give_index in your code) we stop the loop once we find the correct index. Also we avoid the cost of an in_array function call.
We modified the find_index function to start only from the part of the array we haven't checked yet. Leading to a way more efficient way of scan the array.
In the for loop (a while loop was just wrong there) we stored the count of the array once, avoiding multiple calls.
Also we swap the $array2 values only if they are in the wrong place.
Other improvements
If you know anything else of the $array2 array you can make this even more performant. For example if you know that indexes are alternated like in $array1 you can change the main for loop from:
for ($i = 0, $c = count($array1); $i < ($c - 2); $i++) {
to
for ($i = 0, $c = count($array1); $i < ($c - 2); $i+2) {
(notice the $i+2 at the end) And you could do that in the find_index function as well.
Look into usort (http://php.net/manual/en/function.usort.php).
It provides a simple way to sort arrays using a user provided comparison function.

Categories