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

Link to comment
Share on other sites

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!?

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.