I have this problem where I can't get the value from the array in the for loop but I can access it in the while loop.
I can't seem to find a answer online, so help would be much appreciated.
while ($pos = strpos($logTxt, $char, $pos))
{
$t++;
$pos += strlen($char);
$positions[$t] = $pos;
}
for($i = 0; $i < sizeof($positions); $i++)
{
$beginLine = $lastEndLine;
$endLine = $positions[2];
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
I think that this could be pretty easily fixed by using a foreach loop instead of a for loop, because it is an array.
foreach($positions as $position) {
$beginLine = $lastEndLine;
$endLine = $position;
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
If you want to use a for loop still, I believe your problem is you are only referencing the 3rd position of the array (Key 2, as arrays start at 0), not what the loop is pointing to. You could fix it by doing this
for($i = 0; $i < sizeof($positions); $i++)
{
$beginLine = $lastEndLine;
$endLine = $positions[$i];
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
Your $endLine always has third element from array, because of $positions[2]. Try changing it to $positions[$i]
You base problem is using constant index in $positions[2]. But your 1st line in for loop $beginLine = $lastEndLine; will always fail because $lastEndLine is not defined yet. You can use smth like
// beginLine // endLine
$textToEcho = substr($logTxt, $positions[$i-1], $positions[$i]);
of course you need $positions[-1] set to 0 before your first loop or smth like this (it's not clear what's happening before)
UPD I've tried your code and concluded
it will not work at all if $char is the first occurence in $logTxt
it does the nearly the same as explode() function
Related
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.
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";
I've read on a web page, explaining that in PHP it is must faster execution to do a for loop than a foreach. This is new to me, but I would like to test this for himself. How do I convert a foreach into a for loop in PHP? Using the one below as an example:
foreach ($station->ITEMS->ITEM as $trips=>$trip) {
$ny_trips[$trips] = $trip;
}
I've seen for loops in PHP, but not using 'as' in them. So I'm not sure how the above would look in PHP as a for loop. Would it also require doing a count() of $station->ITEMS->ITEM? Thanks!
Assuimg the keys on the array are a perfect numerical sequence starting at 0 then this is what you are looking for.
for($x = 0, $nItems = count($station->ITEMS->ITEM); $x<$nItems; $x++) {
$ny_trips[$x] = $station->ITEMS->ITEM[$x];
}
If the keys are non-numeric then or not in perfect order then you need to do something like this.
$keys = array_keys($station->ITEMS->ITEM);
for($x = 0, $nItems = count($station->ITEMS->ITEM);$x < $nItems; $x++) {
$ny_trips[$keys[$x]] = $station->ITEMS->ITEM[$keys[$x]];
}
for($i=0;$i < count($station->ITEMS->ITEM);$i++){
$ny_trips[$i] = $station->ITEMS->ITEM[$i];
}
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.
I am currently a bit stuck in finding out how to compare these variables against eachother, I have 24 dropdown selections with 24 options to choose from within each one, I then post them to the PHP page. What is the easiest, most efficient way of comparing each of these values against each other to check that each option that is chose is different from each other as none of the 24 options can be the same. I know that an array is the way forward with this, just not sure on how to compare them.
Any help is much appreciated.
$id = $_POST[trackid];
$pos1 = $_POST[pos1];
$pos2 = $_POST[pos2];
$pos3 = $_POST[pos3];
$pos4 = $_POST[pos4];
$pos5 = $_POST[pos5];
$pos6 = $_POST[pos6];
$pos7 = $_POST[pos7];
$pos8 = $_POST[pos8];
$pos9 = $_POST[pos9];
$pos10 = $_POST[pos10];
$pos11 = $_POST[pos11];
$pos12 = $_POST[pos12];
$pos13 = $_POST[pos13];
$pos14 = $_POST[pos14];
$pos15 = $_POST[pos15];
$pos16 = $_POST[pos16];
$pos17 = $_POST[pos17];
$pos18 = $_POST[pos18];
$pos19 = $_POST[pos19];
$pos20 = $_POST[pos20];
$pos21 = $_POST[pos21];
$pos22 = $_POST[pos22];
$pos23 = $_POST[pos23];
$pos24 = $_POST[pos24];
Given an array you could try array_unique function
count($original_array) != count(array_unique($original_array))
Alternative solution with array_count_values
count(array_count_values($original_array)) = count($original_array)
There are lot of way to do that (e.g. a for loop), it just depends from your exact needs.
Firstly, you should be adding quotes around your array indices rather than using barewords which should be raising warnings:
$pos1 = $_POST['pos1'];
To copy the pos* values out of $_POST, you should use a loop:
$pos = array();
for ($i = 1; $i <= 24; ++$i) {
$pos["pos$i"] = $_POST["pos$i"];
}
To make sure there are no duplicates, use array_unique and see if the two arrays have the same length:
if (count(array_unique($pos)) == count($pos)) {
# pos contains no duplicates
}
Just do an array_unique on it. First you'll need to put those POST vars into an array instead of splitting them up.
$pos = array();
for ($i = 1; $i <= 24; $i++)
{
$pos["pos$i"] = $_POST["pos$i"];
}
$unique = array_unique($pos);
if (count($unique) == 24)
{
// all good!
}
else
{
// bad!
}
can you more explicit? if none of them can be the same, than what is the problem?
considering that you actually can select the same option more than once or you just want to protect from attacks, than you can put them into an array, and then use the array_unique function.