how do I make an array position equal a variable - php

what I want to do is run this for loop and within there is a foreach searching the positions. what I want to do is once there it returns false I want it to break and save the position of $i in a variable. I'm using simple_html_dom.php but I don't think that matters since this is more of a basic programming problem.
for($i = $0; $i < $20; $i++){
foreach($html->find('div[class=cate_link]',$i) as $a){
if (strpos($a->plaintext,'+info') == false){
break;
}
}
//this is not valid, but essentialy this is what I want to do.
$stop = $i;
}

To break multiple levels in a loop you simply specify the levels, eg, break 2 - see the manual on break - http://www.php.net/manual/en/control-structures.break.php.
As such your code might work as
for($i = $0; $i < $20; $i++){
foreach($html->find('div[class=cate_link]',$i) as $a){
if (strpos($a->plaintext,'+info') == false){
$stop = $i; // Set variable
break 2; // break both loops
// or alternatively force the outer loop condition to expire
//$i = 21; // Force the outer loop to exit
//break;
}
}
}
I have expanded to question to set $i = 21 to break the outer loop with a single break.

Untested code but syntax checked...
<?php
// Untested code...
// Assume that you WILL break out of the loops...
$currentForIdx = -1; // so we can test that 'for' loop actually ran
$quitLoops = false;
for($i = 0; $i < $20 && !quitLoops; $i++) {
$currentForIdx = $i; // in case we break out of the loops
foreach($html->find('div[class=cate_link]',$i) as $a){
if (strpos($a->plaintext,'+info') == false) {
$quitLoops = true;
break;
}
}
}
// test $quitLoops and $currentForIdx to work out what happened...
?>

I havent tested this, but I would try something like this:
for($i = $0; $i < $20; $i++){
$stop = false;
foreach($html->find('div[class=cate_link]',$i) as $a){
if (strpos($a->plaintext,'+info') == false){
$stop = $i;
}
}
if ($stop !== false) {break;}
}

Related

Multiple comparisons inside for loops don't break php code. Why?

Why this piece of code works when it is clearly wrong in the second for loop (for ($i==0; $i<$parts; $i++) {)?
Does php allows for multiple comparisons inside for loops?
function split_integer ($num,$parts) {
$value = 0;
$i = 0;
$result = [];
$modulus = $num%$parts;
if ($modulus == 0) {
for($i = 0; $i < $parts; $i++)
{
$value = $num/$parts;
$result[] = $value;
}
} else {
$valueMod = $parts - ($num % $parts);
$value = $num/$parts;
for ($i==0; $i<$parts; $i++) {
if ($i >= $valueMod) {
$result[] = floor($value+1);
} else {
$result[] = floor($value);
}
}
}
return $result;
}
Code for ($i==0; $i < $parts; $i++) runs because $i==0 has no impact on loop.
In normal for loop first statement just sets $i or any other counter's initial value. As you already set $i to 0 earlier, your loop runs from $i = 0 until second statement $i < $parts is not true.
Going further, you can even omit first statement:
$i = 0;
for (; $i < 3; $i++) {
echo $i;
}
And loop will still run 3 times from 0 to 2.

I dont know what to do with this PHP Code

The code below basically helps in finding out if a number is a Palindromic Number or not. Although I get my execution done with the output, I just can seem to handle all the "screams" and fatal errors that I get. How do I handle this. Just a beginner and trust you can explain in a way that I may be able to understand..
<?php
for ($num = 1; $num <= 20; ++$num){
$_array1 = str_split($num);
//print_r($_array1);
//echo "<br/>";
$_array2 = array_reverse($_array1);
//print_r($_array2);
//echo "<br/>";
$i = 0;
$j = 0;
while ($i < sizeof($_array1) && $j < sizeof($_array2)){
if ($_array1[$i] == $_array2[$j]){
++$i;
++$j;
}
}
if ($_array1[$i] == $_array2[$j]){
echo "The number $num is a Palindrome Number";
}
}
?>
You get to the size of elements, which is 1. However, if your array has only one element, which is the case for 1-digit numbers, then sizeof($_array) === 1. Which means that the biggest possible index you can use is 0. You need to change your code to something like this:
<?php
for ($num = 1; $num <= 20; ++$num){
$_array1 = str_split($num);
//print_r($_array1);
//echo "<br/>";
$_array2 = array_reverse($_array1);
//print_r($_array2);
//echo "<br/>";
$i = 0;
$j = 0;
$different = false;
while ((!$different) && ($i < sizeof($_array1))){
if ($_array1[$i] == $_array2[$j]){
++$i;
++$j;
} else {
$different = true;
}
}
if (!$different){
echo "The number $num is a Palindrome Number";
}
}
?>
But you are inversing the array without a need to do so and you are looping for unnecessarily long. I propose this function to determine whether an array is a palindrome:
function isPalindrome($input) {
$size = count($input);
for ($index = 0; $index < $size / 2; $index++) {
if ($input[$index] != $input[$size - $index - 1]) {
return false;
}
}
return true;
}
Note, that:
the function assumes that the keys of the array are numbers
the function uses a single array
the size of the array is stored into a local variable to not calculate it repeatedly
the cycle cycles until half of the array, since going beyond that is unnecessary, due to the symmetrical nature of the != operator
the function returns false when the first difference is found, to further optimize the checking
if there were no differences, the function returns true, representing that the input is a palindrome

Sudoku solving/generating algorithm in PHP

I'm having trouble with a specific part of my algorithm and was hoping someone has an idea what I'm doing wrong.
My program basically works like this:
Create 81 empty cells, fill each cell step per step while checking if it's valid there.
I have 3 valid checks and the horizontal valid check (if numbers are double or more in 1 line) is already giving me trouble.
This is my function:
private function isValidHorizontal($index)
{
for ($i = 0; $i < 81; $i += 9){
$firstIndex = $i * 9;
$lastIndex = 9 * ($i + 1) - 1;
// fisrt loop tracking fowards, 2nd loop tracking backwards
if ($index >= $i && $index <= $lastIndex) {
for ($j = 0; $j <= $lastIndex; $j++) {
if ($this->cell[$index]->getValue() == $j) {
return false;
}
}
for ($k = 0; $k >= $firstIndex; $k--){
if ($this->cell[$index]->getValue() == $j) {
return false;
}
}
}
}
return true;
}
$index is the position of the cell so when $index = 0 that would be the very first cell. Last cell would be $index = 80
$this->cell[$index]->getValue() returns an int number i checked so I'm getting the value correctly.
The problem it somehow never returns true
Any Ideas? obviously this is just part of the code, if you need more to help, write a comment and I'll edit :)
In the second inner loop you are using $j instead of $k:
for ($k = 0; $k >= $firstIndex; $k--){
if ($this->cell[$index]->getValue() == $j) { // Here, change to $k
You already got the right answer from #this.lau_, but If I may offer some advice, you could shorten it up a bit by changing the logic. PHP isn't really the best suited language for this, so it'll still look a bit clunky, but I might be worth taking a look at. :)
private function isValidHorizontal($index) {
$taken = [];
foreach (range($index, 81, 9) as $i) {
$value = $this->cell[$i]->getValue();
if (is_int($value) && in_array($value, $taken)) {
return false;
}
$taken[] = $value;
}
return true;
}

How to stop a decreasing iteration after xth element?

So I have a for loop that is decreasing...
for ($i=count($array); i>0; $i--;)
{
if(condition)
{DO SOMETHING like print the element in a decreasing manner}
if(enter ending iteration condition here after xth element) break;
}
that pretty much sums up my question. How do I formulate the ending iteration - let's say after 5 elements printed I want to stop the iteration.
$j = 0;
for ($i=count($array); $i>0; $i--)
{
if(condition)
{
DO SOMETHING like print the element in a decreasing manner;
$j++;
}
if($j > 4){
break;
}
}
Try to reverse the count of the loop. Instead of decreasing, try to increase so you will have a count of how many items are being printed.
<?php
for ($i = 0; $i < count($array); $i++)
{
if(condition)
{
/* DO SOMETHING like print the element in a decreasing manner */
}
/* replace (nth) with the needed number */
if($i === (nth)) break;
}
You could set the limit based on the count, like:
$loop_limit = 5;
$array_count = count($array);
$last = $array_count - $loop_limit;
for ($i = $array_count; $i >= $last ; --$i) {
if ( $i == $last ) {
//Do whatever you need at this point
}
//do the normal loop action
}

PHP substring find infinite loop error

I have this code that for some reason it keeps in an infinite loop, when it is suppose to just print all possible substrings. This is part of the complete function. The purpose of the function is to return the indexes of the substring from string $str2 found in string $str1. Thanks a lot for the help.
$str1='QYDIKYTWNVPKIAPKS';
$str2='KYTWNVPKSS';
print($str1);echo"</br>";print($str2);echo"</br>";
function overlapping($str1,$str2) {
$peptide1 = str_split($str1);
$peptide2 = str_split($str2);
$longest_seq=array();
$len=count($peptide2)-1;
for ($i = 0; $i < count($peptide1); ++$i) {
for ($j = 0; $j < count($peptide2); ++$j) {
if ($peptide2[$j]==$peptide1[$i]){
$k=$j;
$start=$j;
$l=$i;
$tmp=array();
while ($peptide2[$k]==$peptide1[$l]){
array_push($tmp, $peptide2[$k]);
$substring=implode($tmp);
print $substring;
echo"</br>";
$k=$k+1;
$l=$l+1;
}
}
}
}
}
Maybe you have another idea of how to extract the index of a matching substring, I can also try that
You never check to insure that $k and $l are valid offsets. Check for it here :
while (isset($peptide2[$k]) && isset($peptide1[$l]) && $peptide2[$k]==$peptide1[$l]){
instead of
while ($peptide2[$k]==$peptide1[$l]){
I'm not sure if this has anything to do with your issue, but I always post-increment in my for loops.
for ($i = 0; $i < count($peptide1); $i++) {
// do stuff
}

Categories