Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

in_array method on volt

Hi,

How can i use in_array() function on Volt?

I searched on volt doc but i couldnt about that.

I tried in operator but doesnt work with arrays.

{% if id in array %}
    // todo
{% endif %}

Thanks



65.9k
Accepted
answer
edited Sep '16

You have to add it in your Service defintion:

$di->set('view', function() use ($di) {
    $view = new \Phalcon\Mvc\View();
    $view->setViewsDir(__DIR__ . '/views/');
    $view->setLayoutsDir('/_layouts/');
    $view->setLayout('default');

    $view->registerEngines(['.phtml' => function($view, $di) {
        $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
        $options = [
            'compiledPath' => $di->getConfig()->site->path->cache . 'volt/backend/',
            'compiledExtension' => '.php',
            'compileAlways' => $di->getConfig()->debug,
        ];
        $volt->setOptions($options);

        // Extended functions
        $compiler = $volt->getCompiler();
        $compiler->addFunction('in_array', 'in_array');
        $compiler->addFunction('is_dir', 'is_dir');
        $compiler->addFunction('getimagesize', 'getimagesize');
        return $volt;
    }]);

    return $view;
});

Here is a link with all built in Volt functions. https://docs.phalconphp.com/uk/latest/reference/volt.html#functions

To add other functions or create your own refer to the code above.

I'm already using addFunction but i was expecting direct volt feature ;))

edited Sep '16

Nah, not all php functions are registered in Volt. Its not needed, since most are situationaly based and you can easily add them.

edited Sep '16

How about:

{% if array[id] is defined %}

Didn't check it though.

Nice idea also. Works, done it multiple times :)

How about:

``` {% array[id] is defined %} ```

Didn't check it though.

edited Sep '16
{% set myArray = {'Apple', 'Banana', 'Orange'} %}

Doesnt work with that array. My id is value not index.

edited Sep '16

Oh yes, my bad.. Ahmet wanted in_array, not array_key_exists.. So Wojciech solution wont work in your situation :)

Oh, you're right. So i guess you need to use in_array :)

Use array_flip if you know you have unique values to be able to use "{% array[id] is defined %}".