Jump to content

If first/last page in array


renobird
 Share

Recommended Posts

How can I detect (and add additional markup) to the first/last iteration using the API?

Here's an example:

$profiles = $pages->get("/meet-us/executive-profiles")->children("limit=5");

foreach ($profiles as $profile)
	echo "<h2>{$profile->job_title}</h2>".
	"{$profile->biography}";

With raw PHP I would add a counter to the foreach:

$i = 0;
$length = count($profiles);
foreach ($profiles as $profile) {
if ($i == 0) {
	// first
} else if ($i == $length - 1) {
	// last
}
$i++;
}

I'm sure there's a more elegant solution using the API.

I think I need to use $a->$key, but I'm not quite sure how to put it together.

Any guidance would be much appreciated.

:)

Link to comment
Share on other sites

Thanks all — things are becoming a bit clearer now.

I think it's just a matter of convincing my brain to look at things from the perspective of the API and not raw PHP.

I'll study up on the cheat sheet some more, and try not to ask these rudimentary questions. No promises though. :P

  • Like 1
Link to comment
Share on other sites

That's what I had to learn too. You can look at it from a jQuery point of view. Select/find the element you want to use and do something. That's why I posted the cheat sheet. It's pretty straight-forward. I've got a feeling I've barely scratched the surface, but I do see it's potential. That why PW rocks.

  • Like 2
Link to comment
Share on other sites

The best thing I've had fun playing with recently is chaining in PW, and it's worth knowing about. Here's a good, slightly abstract example:

On a large communal news website, an Article page has a PageField called Author - this links to the Author's page. The Author works for a Company - there might be several authors in that company writing on this website and you might be curious and want to find out various things like the following (pretend we're on the article page still):

// Let's find all articles by this author:
$author_articles = $pages->find("template=article,author=$page->author");

// Let's get the company name that this author works for - going through a few pages to get this one - from the article to the the author' page then the company page - all using the incredibly powerful PageField field type 
echo $page->author->company->title; // Ridiculously simple huh?

// Now let's grab a list of other authors from this company - not sure why you would, but you could (the authors are all PW users in this case, so the template is 'users')
$company_authors = $pages->find("template=user,company=$page->author->company");

// And finally let's get a list of all articles written by all authors in this company using $company_authors above
$company_articles = $pages->find("template=article,author=$company_authors");

Now some people might wonder how the last one works - surely $company_authors is an object or array right? Well if you run a simple echo on it, it doesn't spit it's dummy out like PHP normally would, but rather gives you a concatenated list of page IDs in the format: 123|124|1024|456 - the pipe character is used in the last $page->find to mean "OR" so it works perfectly.

And this is why I keep getting excited whenever I work with ProcessWire. I would need literally dozens of lines of code to recreate that example in any other CMS I can think of.

I pulled in the articles and authors by template, but there are various ways of doing it and I just did it with template names as that didn't assume any particular site structure, so it's not necessary to follow that exactly.

Have fun! :)

  • Like 5
Link to comment
Share on other sites

The best bit I find is in this case (or in any ProcessWire code samples for that matter) is that whilst not all of those things would necessarily be that useful in that particular context, you can see how you might just grab a company's users to display on the company page, or company details on the author's page and so on - I just love the ease at which you can get at related content from whatever angle you like in one or two lines of code, just leaving you with the fun job of outputting it on the screen.

Anything that lets someone as impatient as I am output the finished result to the screen in as little time as possible is great, and from a business point of view the hours of work it saves and the legibility of the code that's produced are invaluable, especially when it comes to re-using similar code in other websites.

A fun thing I did recently was to implement a gallery page on a website and that had child pages for different gallery sections. The whole thing took about 20 minutes and about as many lines of PHP and HTML ;)

  • Like 2
Link to comment
Share on other sites

  • 4 years later...

I know this topic is kinda old... ;)

Since this is a othen find on google search on finding/handling first/last entries i will provide a little snippet that get pagefield titles prepared for needed output.

Should just stay as very simple example for using first() and last() on this short thread...

//get the page field titles right with a separating ,
$titles	= '';

//count if we have more than one page in the page field
if (count($page->mypagefield) == 1) {
    //we have only one page so get the first page title
    $titles = $page->mypagefield->first()->title;
} else {
    //we have more pages in the pagefield so lets loop
    foreach ($page->mypagefield as $t) {
        //we need a , after every entry but not in the last one
        if ($t === $page->mypagefield->last()) {
            $titles .= $t->title;
        } else {
            $titles .= $t->title.', ';
        }
    }
}

//output will be  "title1, title2, title3, lasttitle"

best regards mr-fan

EDIT: use arjen's example of implode() is in this case much more smarter....but the example above shows how to work with first() and last() so it will stay ;)

  • Like 1
Link to comment
Share on other sites

Hey mr-fan,

If I understand your case correctly you could use implode() instead of your if else / foreach so you'll save the a few lines. Makes it more readable too:

echo wire('page')->field_name->implode(', ', 'title'); // This will produce title1, title2, title3, lasttitle
  • Like 1
Link to comment
Share on other sites

Always like to learn new things about the API... ;)

but your code gives me a Call to a member function implode() on null error...?

All sorted out your lession is great...no more need for such a PHP function...and replaced with a onliner + API call on implode()!

Great thank you very much!!

$page->yourPageField->implode(', ', 'title');
Edited by mr-fan
Link to comment
Share on other sites

Ok - now with this last link you made a special xmas present in the middle of june... :frantics:

Thank you again for your useful hint.

<ot>...I'm part of this forum for two years, using devns, read every week the interesting topics....and there are still so much hidden goodies </ot>

best regards mr-fan

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...