How can I get only the first two elements of an array by using a foreach loop in PHP?

Related searches

I have an array like this:

$aMyArray = array(
            "bmw"=>"user1",
            "audi"=>"user2",
            "mercedes"=>"user3"
);

And I only want to show the first two elements bmw=>user1 and audi=>user2. But I want it by using a foreach loop.

If you want the first 2 by name:

Using in_array (documentation) is what you looking for:

$aMyArray = array("bmw"=>"user1", "audi"=>"user2", "mercedes"=>"user3");
$valuesToPrint = array("bmw", "audi");
foreach($aMyArray as $key => $val) {
    if (in_array($key, $valuesToPrint))
        echo "Found: $key => $val" . PHP_EOL;
}

If you want the first 2 by index use:

init index at 0 and increment in each iteration as:

$aMyArray = array("bmw"=>"user1", "audi"=>"user2", "mercedes"=>"user3");
$i = 0;
foreach($aMyArray as $key => $val) {
    echo "Found: $key => $val" . PHP_EOL;
    if (++$i > 1)
        break;
}

foreach - Manual, The first form loops over the array given by array_expression. Reference of a $ value and the last array element remain even after the foreach loop. Before PHP 5.5.0, referencing $value is only possible if the iterated array can be foreach example 2: value (with its manual access notation printed for illustration) */ To change the values of array elements inside the loop, you have to use a reference that returns by the foreach loop. To enable the foreach loop to return a reference to the array element, you add an ampersand ( & ) symbol in front of the loop variable as follows:

$counter = 1;
$max = 2;
foreach ($aMyArray as $key => $value) {
    echo $key, "=>", $value;
    $counter++;
    if ($counter === $max) {
        break;
    }
}

It is important to break execution to avoid arrays of any size looping until the end for no reason.

How to display two elements of array at same time using foreach , This is my for each loop, <?php $i = 0; foreach($expression as $key => $item) { ? > How to display two elements of array at same time using foreach loop in php ? then by this loop I should get output like first it will display 1 then +2 should Use the modulo-operator to trigger only odd keys and show the� In PHP 5, when foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop. As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.

<?php
$aMyArray = array(
            "bmw"=>"user1",
            "audi"=>"user2",
            "mercedes"=>"user3"
);

reset($aMyArray);
echo key($aMyArray).' = '.current($aMyArray)."\n";
next($aMyArray);
echo key($aMyArray).' = '.current($aMyArray)."\n";

Using PHP foreach Loop to Iterate over Elements of an Array, The foreach loop statement only works with arrays and objects. 1. 2. 3. 4. <? php. foreach ($array as $element) {. // process element here;. } In the first iteration, we assigned $score the first element of the $scores array and because $score is� The foreach loop provides a simple, clean way to iterate through the elements of an collection or an array of items. One thing we must know that before using foreach loop we must declare the array or the collections in the program. Because the foreach loop can only iterate any array or any collections which previously declared.

Easiest way:

$aMyArray=array("bmw"=>"user1","audi"=>"user2","mercedes"=>"user3");
$i=0;
foreach ($aMyArray as $key => $value) {
 if($i<2)
 {
    echo $key . 'and' . $value;
 }
 $i++;
}

Iterate associative array using foreach loop in PHP, Both arrays can combine into a single array using a foreach loop. Array: Arrays in PHP is a type of data structure that allows to storing multiple elements of� In Counting PHP Array Elements Using count(), I showed how you can use a for loop along with the count() function to loop through an array. However, there’s a much easier way to loop through arrays: the foreach construct.

I know you're asking how to do it in a foreach, but another option is using array travelling functions current and next.

$aMyArray = array(
            "bmw"=>"user1",
            "audi"=>"user2",
            "mercedes"=>"user3"
);
$keys = array_keys($aMyArray);
//current($array) will return the value of the current record in the array. At this point that will be the first record
$first = sprintf('%s - %s', current($keys), current($aMyArray)); //bmw - user1
//move the pointer to the next record in both $keys and $aMyArray
next($aMyArray);
next($keys);
//current($array) will now return the contents of the second element.
$second = sprintf('%s - %s', current($keys), current($aMyArray)); //audi - user2

How to get the first element of an array in PHP?, Some of the methods are using foreach loop, reset function, array_slice function, array_values, array_reverse and many more. By direct accessing the 0th index:. The number of times the foreach loop will execute is equal to the number of elements in the array or collection. Here is an example of iterating through an array using the for loop: Example 1: Printing array using for loop

Given two arrays arr1 and arr2 of size n. The task is to iterate both arrays in the foreach loop. Both arrays can combine into a single array using a foreach loop. Array: Arrays in PHP is a type of data structure that allows to storing multiple elements of similar data type under a single variable thereby saving the effort of creating a different variable for every data.

I often loop over an array to find an element that matches criteria. In a classic for loop you can set the index to the array length to stop execution. You can also use a break statement to stop the for loop. This can't be done with forEach. Instead you may want to think about using the array filter as an alternative.

A Loop in PHP is an Iterative Control Structure that involves executing the same number of code a number of times until a certain condition is met. PHP For, ForEach, While, Do While loop

Comments
  • Possible duplicate of How does PHP 'foreach' actually work?
  • What exactly is the logic that you are looking for? Should the loop stop when encountering the key mercedes? Do you only want the values where the keys are bmw and audi? Or do you only want the first 2 items from the array? Can you share any attempts?
  • dunno if this is the logic your looking for: 3v4l.org/2sRDQ
  • I want to echo only bmw and audi
  • @cbk38 yes but you can do it by e.g. checking the key for the value "mercedes" or by checking the key for one of the values ("bmw", "audi") or by only printing the first two in any case, or by printing all except the last, or by removing the last entry from the array before iterating. All those will give you the same result by applying different logic
  • OP request using for-loop (I do agree this is better solution...)
  • Why exit instead of a break?
  • Are you sure about this? What if the keys changed?
  • This is only the idea you can change your code as per your need