0

I have an array called $list that returns multiple values, I'm looping through this and displaying these values. I need to edit one of the original values.

Here's the result of;

print("<pre>".print_r($list,true)."</pre>");

Array
(
    [0] => stdClass Object
        (
            [name] => Home
            [link] => /example/
        )

    [1] => stdClass Object
        (
            [name] => Items
            [link] => /example/locations/items   <-- I want to edit this value
        )

    [2] => stdClass Object
        (
            [name] => Paris
            [link] => /example/locations/paris
        )

)

The code below;

foreach ($list as $key => $item) {
    echo $item->link;
}

Produces;

  • /example/
  • /example/locations/items
  • /example/locations/paris

I need to edit the link value IF the name key is Items. I essentially want to remove the last URL parameter so the output looks like this;

  • /example/
  • /example/locations
  • /example/locations/paris

Note that it will not always be position [1] in the array, but the name value will always be Items.

How can I achieve this?

1 Answer 1

2

You could use array_walk, passing it a function which checked for the name key being Items and if so returning the dirname of the link key:

array_walk($list, function (&$v) { if ($v->name == 'Items') $v->link = dirname($v->link); });

Output:

Array
(
    [0] => stdClass Object
        (
            [name] => Home
            [link] => /example/
        )    
    [1] => stdClass Object
        (
            [name] => Items
            [link] => /example/locations
        )    
    [2] => stdClass Object
        (
            [name] => Paris
            [link] => /example/locations/paris
        )    
)

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.