0

I have come across a PHP foreach statement that I am having trouble finding any documentation on.

Here is the code I am having trouble understanding:

<?php foreach((array)$this->item->partno as $value): ?>
    // do some stuff
<?php endforeach; ?>

What is the (array) doing and what is happening with this foreach?

4
  • 1
    It is just saying the item is an array and the foreach is getting a value from the array on each iteration. Commented Apr 11, 2018 at 17:51
  • Seems like a basic search could have helped here. Commented Apr 11, 2018 at 17:51
  • 1
    @Adam - not if you don't know what the terminology is. What should he search for if he doesn't know what it's called? Commented Apr 11, 2018 at 17:52
  • @Utkanos - if you understand basics of programming, you could understand this is casting an object. Commented Apr 11, 2018 at 17:53

2 Answers 2

3

You're casting (converting) whatever the type of $this->item->partno is, in an array.

More on this in the php docs here

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

Comments

1

This technique is useful when you have a function and you want it to take an argument that can be either a single value or an array. For example, you might normally do something like this:

function foo($items) {
    if (!is_array($items)) {
        $items = array($items);
    }
    foreach ($items as $item) {
        // ...
    }
}

By casting the variable to an array inline, you can avoid the explicit array check, and the code will work fine if you pass it either a single value or an array:

function foo($items) {
    foreach ((array) $items as $item) {
        // ...
    }
}
foo(1);
foo([1, 2, 3]);

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.