Jump to content

What's wrong with this foreach & array ??


doa24uk

Recommended Posts

As you can see, the Target is 3.com and it IS in the array ... so why isn't this working??

 

It's continuously outputting Not Found

 

:shrug: :shrug: :wtf: :wtf:

 

<?php
$Target="3.com";
$arr=array("http://1.com","http://2.com","http://www.3.com/whatever","http://4.com");

foreach($arr as $key => $value);
{
     if(stristr($value, $Target))
{
$Position = $key;
}
else
{
$Position = "Not Found";
}
echo $Position;
}
?>

Link to comment
https://forums.phpfreaks.com/topic/195868-whats-wrong-with-this-foreach-array/
Share on other sites

You shouldn't have the semicolon after your foreach.  Also, you need a break.

 

$Target="3.com";
$arr=array("http://1.com","http://2.com","http://www.3.com/whatever","http://4.com");

foreach($arr as $key => $value)
{
if(stristr($value, $Target))
{
	$Position = $key;
	break;
}
else
	$Position = "Not Found";
}
print $Position;

Thanks, just expanding this slightly - that loop is actually within another loop.....

 

$Target = "phrase 2"
$textarea_array=array("phrase 1","phrase 2");

foreach ($textarea_array as $XQuery) {


$html = "http://www.mysite.co.uk/search?api=" .$XQuery;
$dom = new DOMDocument;
@$dom->loadHTMLFile($html);
$xpath = new DOMXPath($dom);
$aTag = $xpath->query('//h3[@class="r"]/a');
foreach ($aTag as $val) {
     $arr[] = $val->getAttribute('href');
}
foreach($arr as $key => $value)
{
if(stristr($value, $Target))
{
$Position = $key;
break;	
}	
else {
$Position = "Not Found";
}
}
echo $XQuery;
echo "-";
echo $Position;
echo "<br><br>"; 
}

 

What should be being output is

 

phrase 1 - position of phrase 1

phrase 2 - position of phrase 2

 

What is actually being output is

 

phrase 1 - position of phrase 1

phrase 2 - position of phrase 1

 

And I just can see why!?

I'm assuming that's sanitized and you aren't posting the true code.  That makes it a little more difficult to diagnose, because the values you're passing could be causing an issue.  The site that you're posting to could be returning data that's causing the problem.

 

Nothing is jumping out at me, with the code you posted.  Can you post the real code?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.