Kamil Grzechulski Kamil Grzechulski - 17 days ago 11
PHP Question

PHP - show 'echo' one time in for loop

Today i'am using PHP DOMDocument class to find all link's in source code.
$links array have all links from site. Function 'for' use loop iteration for find given $domain.

echo 'Find link: ' . $domain . '';
echo "<b>Status: ";

//$links is array with all links
//$domain is domain for example : http://example.com

for($i = 0;$i<count($links);$i++)
{
$find_href = preg_match("@$domain@i", $links[$i]['href']);

if($find_href)
{

if($links[$i]['href'] != "")
{
echo $links[$i]['anchor'];
echo 'Link found';'
}
else
{
echo 'Link not found';
}


Example:

searched domain: http: //example.com
searched url: http: //www.iana.org

Result:

Link not found
Link not found
Link not found
Link not found
Link not found
http://www.iana.org/domains/example
Link found // find bacouse link is in source code of http://example.com
Link not found
Link not found
Link not found
Link not found
Link not found
Link not found
Link not found


searched domain: http://example.com
searched link: http://google.com

Result:

Link not found
Link not found
Link not found
Link not found
Link not found
Link not found
Link not found
Link not found
Link not found
Link not found


If $domain not found in $links array, How to print one time "Link not found" ?

Answer

Simply register a found condition in a variable and then output the not found messages after the loop is complete based on whether you found something.

echo 'Find link: ' . $domain . '';
echo "<b>Status: ";

//$links is array with all links
//$domain is domain for example : http://example.com

$found = false;

for($i = 0;$i<count($links);$i++) {
    $find_href = preg_match("@$domain@i", $links[$i]['href']);

    if($find_href) {

        if($links[$i]['href'] != "") {
            echo $links[$i]['anchor'];
            echo 'Link found';
            $found = true;
        }
    }
}
if (!$found) {
    echo 'Link not found';
}

Picking up on the comments received this would be better code

echo 'Find link: ' . $domain . '';
echo "<b>Status: ";

//$links is array with all links
//$domain is domain for example : http://example.com

$found = false;

foreach ($links as $link) {
    $find_href = preg_match("@$domain@i", $link['href']);

    if($find_href) {
        if($link['href'] != '') {
            echo $link['anchor'] . "\nLink found";
            $found = true;
        }
    }
}
if (!$found) {
    echo 'Link not found';
}