Skip to content
Advertisement

Foreach last item gets methode

Guys I have an array with objects, I want the last item in the foreach loop do something else then the rest. How do I archive that?

if(sizeof($testDup) > 3){
    } else {
        foreach ($testDup as $d) {  
        }
    }

$test array(3)
    432 => test_id -> 21
    431 => test_id -> 21
    435 => test_id -> 21

Advertisement

Answer

This will process the array of objects and do something else with the last element:

    $data = '';
    $arrayWithObjects = array(
        (object)array('test1', 'test2'),
        (object)array('test1', 'test2'),
        (object)array('test1', 'test2'),
    );

    foreach ($arrayWithObjects as $object) {
        // Can't get next in the array, so is last element
        if (!next($arrayWithObjects)) {
            // Process last element
            $data .= $object->{1};
        } else {
            // Process all other elements
            $data .= $object->{0};
        }
    }

    var_dump($data); // "test1test1test2"
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement