Access variable from foreach loop in a page method not possible?

Hi,

I am trying to build a page method – thesymbol() – that outputs a <svg> that represents page meta-data in an abstract way.

So far my complete page-methods php looks like this (ignore the cover function):

<?php

Kirby::plugin('my/page-methods', [
    'pageMethods' => [
        'cover' => function () {
            return $this->content()->get('cover')->toFile() ?? $this->image();
        },

        'thesymbol' => function (array $pointinput = [], $canvassize = 100) {
            $alphabet = array_merge(range('A', 'Z'),range('a', 'z'),range('0', '9'));
            if (count($pointinput) < 0) {$pointinput = [$this->title()];};
            $pointsteps = count($pointinput);
            $canvassize -= 10;

            $html = '';
            $pointvalues = array();

            for ($i = 0; $i < $pointsteps; $i++) {
                
                $letters = str_split(strtoupper($pointinput[$i]));

                $counter = 0;

                foreach ($letters as $letter) {

                    $letternumber = array_search($letter, $alphabet)+1;
                    $letternumber = false ? $letternumber = 50 : $letternumber;
                    $pointvalues[] = round(($letternumber / (count($alphabet) / $canvassize)),0).','.round(((($i+$counter) / (count($letters) / ($canvassize)))+5),0);
                    $counter++;
                } 
            }

            $html .= '<div class="lines">';
            $html .= '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' . ($canvassize + 10) . ' ' . ($canvassize + 10) . '" preserveAspectRatio="xMidYMid meet">';
            $html .= '<polyline fill="none" stroke="#000" points="'.implode(' ', $pointvalues).'" />';
            $html .= '</svg">';
            $html .= '</div">';
            
            return $html;
        }
    ]
]);

It return the html fine, however the $pointvalues array doesn’t seem to be updated at all and implode(' ', $pointvalues) outputs nothing.

I started with a snippet which worked but I realised that I cannot use it multiple times in a template, thus I rebuild it in a page-method.

Am I on a completely wrong track here?
I cannot figure out why it isn’t working. I don’t get error messages or anything.
Using global within the loops doesn’t do the trick …

This condition will never be true.

And there are some syntax issues in your html, like </div">, <svg">.

Consider moving the HTML into a snippet to avoid error prone string concatenation.

Hi Texnixe,

thank you so much!

It works now.

I’m trying to rewrite it with a snippet as you suggested, since I also really dislike this way, but didn’t know better.