Breaking a foreach loop - php

I was unable to break out of a foreach loop. I think the structure is correct there is something else wrong with the code. Please let me know what is the issue,(not just a working code) i want to learn from my mistakes. Thanks
I am using simple html dom for scraping some piece of information and i want the loop to break when a condition is matched. Here is my code :
<?php
$mainjob = file_get_html('link to scrap here');
$newarr = array();
foreach($mainjob->find('td[valign=middle]') as $d) {
$data = $d->innertext;
$newarr[] = $data;
echo $data . "<br>";
if($data == "Job Opportunity Description:") {
break;
}
}
print_r($newarr);

1) I guess your $data=="Job Opportunity Description:" condition wasn't true, so it didn't call the break;
2) Put your $mainjob->find('td[valign=middle]') out of your loop conditions, so it doesn't get called each iteration:
$tds = $mainjob->find('td[valign=middle]');
foreach($td as $d){}
3) Why did you add brackets to your $newarr variable?
4) Maybe your $data string still contains the html tags (which aren't shown by echo due to your browser.. so the condition would return false.

The problem is in the white space i used trim() to trim out the white space and it works. I recommend the answer from Ayman Safadi. Thanks.

Related

Want Program logic in PHP To display string

I am having input as Word "CODE"
and I want to get output as "CCOCODCODE"
Please help me with the logic to print this output.
Thanks.
It's rather simple. Looking at your pattern, you need to concatenate all possible prefixes of CODE one after the other. So, maintain a result variable and keep concatenating substrings with 0 as the start point and end point being each index in the string.
<?php
$str = 'CODE';
$result = '';
for($i=0;$i<strlen($str);++$i){
$result .= substr($str,0,$i+1);
}
echo $result;
Try to avoid loops whenever you can.
Short and simple does the trick :-)
<?PHP
$Text = 'CODE';
echo implode(array_map(function($Position) use ($Text) { return substr($Text,0,$Position+1); },array_keys(str_split($Text))));

Can anybody help me with an issue regarding checking to see if an array of strings exist within a string?

What I am doing is looping through an object of tweets, and within each iteration I am checking to see if the tweet contains any words stored in an array.
This example shows the preg_match, however I am having the same issue if I use strpos() or stripos() instead.
Here is the function:
function contains($tweet, $words) {
$count = 0;
foreach($words as $word) {
if (preg_match('/'.$word.'/',$tweet)) {
$count++;
}
}
return $count;
}
The problem is that it's not going through the if statement unless I hard code in a word. $word DOES contain the correct values and are definitely strings as I have tried echoing and var_dumping out the value in the loop.
Usage:
$results = $twitter->request('search/tweets', 'GET', $parameters);
$negative_words = file("negative-words.txt");
foreach($results->statuses as $tweet) {
echo contains($tweet->text, $negative_words);
}
I have tried searching around and tried many different approached and nothing has worked yet. Does anybody know what the issue might be?
Working example:
<?php
function contains($tweet, $words)
{
$count = 0;
array_walk($words,function($word) use(&$count,$tweet){
if(strpos($tweet,$word)!==false){
$count++;
}
});
return $count;
}
There were some SNEAKY carriage returns on the end of the strings returned by the list. The issue was resolved by removing them using str_replace().

lost var in php

I am fairly new to PHP and Yii, and the problem that I am not nor as the question in google, so the only thing I can think of is to ask the question to this list that I have solved many problems.
The issue is as follows: in the code that I attached, I read several records that I keep in array and after the process.
Well, if you look at the debug entries in foreach in he first, all goes well and the variable $items is loaded, but when I get to the second debug $items variable has the correct number of elements, but the elements are empty : count ($items) = 2 but $items[0] and $items[1] are null
$idiomas=CListaMidiomas::model()->findAll();
$items=array();
$nombre=array();
$a=0;
foreach ($idiomas as $idioma){
$nombre[$a]=$idioma->sIdioma;
$items[$a]=TblCategoriastexto::model()->findAll(
array('condition'=>'id='.$data->id.' AND idIdioma='.$idioma->id_idioma));
echo "<br>---AAAAAAAAAAA--".$a."-----------<br>";
CVarDumper::dump($items); //in this moment is correct
if (empty($items[$a]) ||$items[$a]==null ){ // not enter because $items have content
$items[$a]=new TblCategoriastexto();
$items[$a]->idIdioma=$idioma->id_idioma;
}
$a++;
}
echo ">>>>>>>>>>>>>>>".count($items) ; //<<<<<<<<<<present 2
CVarDumper::dump($items); // but in this moment t0 2 are null
for ($a=0;$a<count($items) ;$a++){
echo "<b>".CHtml::encode($nombre[$a]).":</b>";
$out="";
$item=$items[$a];
echo "<br>-----".$a."-----------<br>";
CVarDumper::dump($items[$a]);<<<<<<<<<<<<<<<<<<<<<<<<null
for ($b=1;$b<=20;$b++){
$campo="tc".$b;
$out.=$items[$a]->$campo . ",";<<<<<<<<<<<<<<<<error
}
echo CHtml::encode($out);
echo"<br>";
}
This line: if (empty($items[$a]) ||$items[$a]=null ){ will always assign $items[$a] to null.
To compare values, use the comparison (for equality) operator, == instead of the assignment operator =.
Try changing this line:
if(isset($items[$a]->$campo)) {
$out.=$items[$a]->$campo . ",";
}

Access variable from inside a nested foreach statement PHP

I am getting the key from a given value in a multidimensional array. It works fine except that I cannot seem to access the variable from OUTSIDE the nested foreach loop that I'm using to get the key.
so my foreach loop is: ($name_books is the multi-d array which contains 3 smaller arrays)
foreach($name_books as $test) {
foreach ($test as $key => $value) {
$book_code = array_search($row['name'],$test);
echo $book_code; //just to see if it works, which it does
break;
}
}
//But then if I go outside of the loop..
echo $book_code." is the book code"; // <--DOES NOT WORK
So I know that I'm dealing with variable scope issues here and I've tried declaring globals inside the foreach loop but nothing works.
I'm sure there is something absurdly simple I'm missing!
EDIT:
urg..I took a step back and realized something else,
all this is happening inside a while loop (getting stuff from a db)
so the code is more like:
while($row=mysql_fetch_assoc($result)) {
...original foreach loop from above
}
apologies for not including this, I was focusing on this tiny piece and forgot to back up and see where it fit.
break;
Will only exit the internal nested foreach. If there are more rows in $name_books, it will continue looping and eventually overwriting $book_code with 'false' values from array_search;
Once you've found the value you're looking for, use:
break 2;
Regarding your edit, where you break depends on what you're doing with the value you've found for $book_code. If you don't plan on continuing, change the parameter for break. break 3; will exit the while loop too. Change the value depending on the level of nesting.
This has nothing to do with variable scope so long as what you posted is exactly what you have in your script.
I think what the problem is, is that you are only breaking out of the inner loop. In each iteration of the outer loop, $book_code will get changed, so you need to stop the outer loop as well. Try changing break; to break 2; and see if it fixes your problem. That causes it to break out of both the inner and the outer loop.
Edit: I think you can also simplify your code:
foreach ($name_books as $test) {
$book_code = array_search($row['name'], $test);
if ($book_code !== FALSE) {
break;
}
}If I knew more about your structure, this could possibly be reduced down to a single SQL statement and 0 loops.
simshaun is right, but I would actually take a different approach.
I would check for the existence of $book_code in my foreach loops rather than dealing with the breaks.
New Code
foreach($name_books as $test) {
foreach ($test as $key => $value) {
if(!isset($book_code)){
$book_code = array_search($row['name'],$test);
echo $book_code; //just to see if it works, which it does
}
}
}
echo $book_code." is the book code";

Stop processing and evaluate next value in foreach loop

I am trying to search and check for the duplicate details that is available in the database using php.The user enters several names and then a phone number to check for the duplicates. Below is my function. I just cropped out some parts because it was too long.
function gtc($names,$phone)
{
$pageNumb=20;
$position = array(5);
$sepname=explode(",","$names");
foreach ($sepname as $sepname1)
{
for ($page=0;$page<=$pageNumb;$page=$page + 1)
{
$turl="http://192.168.111.2119/search.php?qry=$sepname1&page=$page";
$search=curl_init();
curl_setopt($search,CURLOPT_URL,$turl);
curl_setopt($search,CURLOPT_RETURNTRANSFER,1);
curl_setopt($search,CURLOPT_FAILONERROR,true);
curl_setopt($search,CURLOPT_AUTOREFERER,true);
$result=curl_exec($search);
$dom = new DOMDocument();
#$dom->loadHTML($result);
$xpath=new DOMXPath($dom);
$elements = $xpath->evaluate("//div[#id='inf']");
foreach ($elements as $element)
{
$position[$sepname1] = $position[$sepname1] + 1;
foreach($position as $key=>$val)
$contct = $element->getElementsByTagName("contact")->item(0)->nodeValue;
if (preg_match("/$phone/i",$contct)) {
echo "Found In Database>";
}
}
ob_flush();
flush();
}
}
}
?>
The function works perfectly but the only problem that I am having is although a match is found it goes until the last page which is given in the for loop and then goes through the next name. I would like to know is it possible to make when a match is found stop processing and then search for the next name?
I don’t want to use exit(); because it completely stops the execution
The input format is as below
User inputs names: john, Sam, Michael, Steve
Phone number:0084554741
Any help will be appreciated
You are likely looking for break
break ends execution of the current for, foreach, while, do-while or switch structure.
// output numbers 1,2,3,4
foreach( range(1,10) as $number) {
if($number === 5) break;
echo $number, PHP_EOL;
}
and/or continue
continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
// output only even numbers
foreach( range(1,10) as $number) {
if($number % 2) continue;
echo $number, PHP_EOL;
}
#Gordon offered the formally correct answer, a "best practices" answer would be to split your function into logical parts (especially as you mention it's too long), for example:
function search($term) {
$xml = loadXmlFromRemoteHost();
if(!$xml)
echo "An error occured";
$found = findTermInXml($xml, $term);
if($found)
echo "Found In Database>";
The search function contains the loop in question and uses "return" to exit the loop (and the function) when it finds something:
function findTermInXml($xml, $term) {
foreach(...whatever...) {
if(...some condition...)
return true;
}
return false; // nothing found
}
Take a look at:
http://pl.php.net/break
http://pl.php.net/continue

Categories