how to terminate array_walk on first loop?

350 Views Asked by At

I need to print only one sub_title of first child(1955) array.

Here is some sample code (that works) to show what I mean.

$array = Array
(
    [1955] => Array
        (
            [sub_title] => subtitle
            [sub_content] => content
        )
    [1957] => Array
        (
            [sub_title] => subtitle
            [sub_content] => conent
        )
    [1958] => Array
        (
            [sub_title] => subtitle
            [sub_content] => conent
        )
)
array_walk($array, function($item){
    echo $item['sub_title'];
    break;
});
2

There are 2 best solutions below

0
Viktar Pryshchepa On BEST ANSWER

As far as I understand your task, you need to get the first element of the array. Use reset(array $array) function to get the first element, than get the value. So your code should look like $fistElement = reset($array); echo $firstElement['sub_titile']; Please also read the documentation on array function and don't try to sew with a hammer

8
yunzen On

You should create a global boolean variable which acts as a flag

<?php
$walk_arr = [
    0 => "A",
    1 => "B",
    3 => "D",
    5 => "F",
];
global $stop_walk;
$stop_walk = false;
$walk_func = function(&$v, $k) {
    global $stop_walk;
    if ($k === 3) {
        $stop_walk = true;
    }
    if ($stop_walk) { 
        return;
    }
    $v .= " changed";
};
unset($stop_walk);

array_walk($walk_arr, $walk_func);
print_r($walk_arr);
print $stop_walk;

See it in action: https://3v4l.org/6kceo

BTW: Can't you just output the first row?

echo $array[1995]['sub_title']