M
M
midarovrk2015-10-13 17:25:47
PHP
midarovrk, 2015-10-13 17:25:47

How to output only the first line in php foreach?

I have a php code that pulls all links to images from the page:

<?php
$content = file_get_contents('http://site.ru');
preg_match_all('/<img[^>]+src="?\'?([^"\']+)"?\'?[^>]*>/i', $content, $images, PREG_SET_ORDER);
foreach ($images as $image) {
    echo $image[1] . '<br>';
}
?>

Here is an example: c11634.shared.hc.ru/cmxrd4.php
How to make the page display only the first line? Those. only the first image, the rest are not needed.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
keslo, 2015-10-13
@midarovrk

In this case it is possible to do without foreach?
echo $images[0][1]. '<br>';

A
Andrew, 2015-10-13
@R0dger

if (isset($images[0])) {
echo $images[0] . '<br>';
}

V
VisualIdeas, 2015-10-13
@VisualIdeas

If it is critical for you to save your code, then just do this:

<?php
$content = file_get_contents('http://site.ru');
preg_match_all('/<img[^>]+src="?\'?([^"\']+)"?\'?[^>]*>/i', $content, $images, PREG_SET_ORDER);
foreach ($images as $image) {
    echo $image[1] . '<br>';
    break;
}
?>

A
Artem Spiridonov, 2015-10-13
@customtema

$first_item = array_shift($list);
Correct, because regardless of the index of the first element of the array (there may not be a zero element, for example, as a result of its intentional removal).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question