LAPS Posted December 4, 2018 Posted December 4, 2018 Hi, in my template file I state the following code: // File: template_name.php $files->include('path/to/filename', array( 'key1' => "Some text value 1", // e.g. $page->title 'key2' => "Some text value 2", // e.g. $page->getLanguageValue('default', 'title') 'keyN' => "Some text value N" )); In path/to/file_name.php I state the following code: // File: path/to/file_name.php $key1 = $vars['key1'] | "Default1"; $key2 = $vars['key2'] | "Default2"; $keyN = $vars['keyN'] | "DefaultN"; // ... echo $key1 . "<br>"; echo $key2 . "<br>"; echo $keyN . "<br>"; // ... When I render the above code in the front-end then I get the text values changed! That is, it outputs something like the following: Rdfs~{{ value1 GDdfgsd value2 dfd]~df value3 Am I doing something wrong? Update In path/to/file_name.php just use ?: instead of |, this way: // File: path/to/file_name.php $key1 = $vars['key1'] ?: "Default1"; $key2 = $vars['key2'] ?: "Default2"; $keyN = $vars['keyN'] ?: "DefaultN"; // ... echo $key1 . "<br>"; echo $key2 . "<br>"; echo $keyN . "<br>"; // ... PHP matters...
MoritzLost Posted December 5, 2018 Posted December 5, 2018 Just for the curious, your garbled text error was caused by using the wrong operator. A single pipe character (|) is the bitwise OR-operator in PHP. Bitwise operators perform comparisons on the bits of integer values. They aren't really useful for strings, as the results are pretty much random. From the PHP manual: Quote If both operands for the &, | and ^ operators are strings, then the operation will be performed on the ASCII values of the characters that make up the strings and the result will be a string. What you were looking for is probably the logical OR operator (||). However, your original $key1 assignment still wouldn't work because of operator precedence in PHP: $key1 = $vars['key1'] || "Default1"; // executed as $key1 = ($vars['key'] || "Default1"); In this case the OR operation will be executed first, and the expression will always evaluate to true because non-empty strings are true-ish. Then the result of the expression is assigned to $key1. A cleaner way that works and will never throw errors: $var1 = !empty($vars['key']) ? $vars['key'] : 'Default1'; In PHP 7 you can use null coalescing: $var1 = $vars['key'] ?? 'Default1'; Keep in mind that this will only assign the default value if $vars['key'] is NULL, but not if it is (int) 0 or an empty string! 2
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now