Answer the question
In order to leave comments, you need to log in
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>';
}
?>
Answer the question
In order to leave comments, you need to log in
In this case it is possible to do without foreach?echo $images[0][1]. '<br>';
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;
}
?>
$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 questionAsk a Question
731 491 924 answers to any question