Web Development Articles

PHP Null Coalescing (??) vs Elvis Operator (?:)

0 👍
👎 0
 Laravel
 PHP

PHP Null Coalescing (??) vs Elvis Operator (?:)

Both operators handle null/empty values but with important differences in behavior.

 

Null Coalescing (??)

The null coalescing operator was introduced in PHP 7.  It returns the first operand if it exists and is not NULL, otherwise it returns the second operand.

- Checks if left operand is set and not NULL

- Returns left operand if it exists and is not NULL

- Returns right operand otherwise

- Does NOT consider empty strings, 0, false as "empty"

 

 // Sample usage below.  If is $beast IS NOT set a warning will be thrown.

 $pet = "puppy";

 $beast = null;

 echo "Result: " . ($beast ?? $pet) ."\r\n"// Result: puppy

 


Elvis Operator (?:)

The ternary operator shorthand checks for truthy values (not just NULL).

- Checks if left operand is truthy (not empty, not zero, not false, not NULL)
- Returns left operand if it's truthy
- Returns right operand otherwise
- Considers empty strings, 0, false as "empty"

 

 // Ternary Operator sample usage

 $pet = "kitty";

 $beast = ""

 echo "Result: " . ($beast ?: $pet) ."\r\n"; // Result: kitty

 

 $beast = "tiger";

 echo "Result: " . ($beast ?: $pet) ."\r\n"; // Result: tiger

 



Choose an operator to use based on whether you need to distinguish between NULL and other "empty" values in your specific use case.

- Use Null Coalescing when you only want to handle NULL values specifically

- Use Elvis Operator when you want to handle all "empty" values

- Null Coalescing is safer for undefined variables (no warnings)

- Consider using null coalescing with arrays and object properties that might not exist

 

Javascript Map, Filter, Reduce methods

0 👍
👎 0
 MongoDB

Map

The map() method is used for creating a new array from an existing one, applying a function to each one of the elements of the first array.

let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(num => num * 2);
console.log(doubled) // [2, 4, 6, 8, 5] 

Filter

The filter() method takes each element in an array and it applies a conditional statement against it. If this conditional returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.

const numbers = [1, 2, 3, 4];
const odds = numbers.filter(num => num % 2 === 1);
console.log(odds); // [1, 3]

Or with an array of Objects you can implement filter() like the following.  

const students = [
{name: 'eric', age: 12},
{name: 'Jenny' age: 11},
{name: 'Freddy', age: 9}
];
const overTen = students.filter(student => student.age > 10); console.log(overTen); // [{name:'Eric', age:12}, {name:'Jenny', age:11}]

Reduce

The reduce() method reduces/calculates a value down to a single value. To get the output value, it runs a reducer function on each element of the array.

const array1 = [1, 2, 3, 4];   // 0 + 1 + 2 + 3 + 4
const initialValue = 10;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + (currentValue * 10), 
initialValue
);

// Expected output is 110.  Ok so the accumulator starts at the value of zero.  And then accumulator is accumulator plus currentValue times 10.  Add 10(initialValue... we set it to 10) + 10 + 20 + 30 + 40

 

Scoped Slot in Vue 2 (Options API)

0 👍
👎 0
 Laravel
 VueJS
 Javascript

With scoped slots, the child component can pass data to the slot content in the parent. That way, the parent can decide how to render data coming from the child.

 

1. Child Component (List.vue)

 

 <template>

   <ul>

     <!-- we expose each item to the slot -->

     <li v-for="(item, index) in items" :key="index">

       <!-- default slot gets props -->

       <slot :item="item" :index="index">

         <!-- fallback content if parent doesn't use scoped slot -->

         {{ index }} - {{ item }}

       </slot>

     </li>

   </ul>

 </template>

 

 <script>

  export default {

    name: "List",

    props: {

      items: {

        type: Array,

        required: true

      }

    }

  }

 </script>

 

 

2. Parent Component (App.vue)

 

 <template>

   <div>

     <h1>Scoped Slots Example</h1>

 

     <!-- Using scoped slot -->

     <List :items="categories">

       <template v-slot:default="slotProps">

         <!-- slotProps.item and slotProps.index come from child -->

         <strong>{{ slotProps.index + 1 }}.</strong> {{ slotProps.item.toUpperCase() }}

       </template>

     </List>

 

     <!-- Without scoped slot (fallback from List.vue will be used) -->

     <List :items="tags" />

   </div>

 </template>

 

 <script>

 import List from "./List.vue";

 export default {

    name: "App",

    components: { List },

    data() {

       return {

         categories: ["News", "Sports", "Entertainment"],

         tags: ["vue", "laravel", "slots"]

       };

    }

 }

 </script>

 

 

What is the PHP Spread Operator (...)

0 👍
👎 0
 PHP

Spread Operator (...)

The PHP Spread Operator (...) is a powerful feature introduced in PHP 5.6 that allows you to "unpack" or "spread" elements from arrays and traversable objects. It's also known as the splat operator or unpacking operator.

The spread operator is particularly useful in modern PHP development for creating more expressive and efficient code when working with arrays and variable function arguments.

Key Benefits of the PHP Spread Operator

  1. Cleaner syntax for array merging and function calls

  2. Better performance in some cases compared to array_merge()

  3. More readable code when dealing with multiple arrays

  4. Flexible for both array operations and function arguments


Here are a few common use cases for the operator:

Unpack and Merge Multiple Arrays

Here are a couple of examples for unpacking and merging arrays.  

 

 $array1 = [1, 2, 3];

 $array2 = [4, 5, 6];

 $array3 = [7, 8, 9];

 

 $merged = [...$array1, ...$array2, ...$array3];

 

 // Array (

 //  [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5

 //  [5] => 6 [6] => 7 [7] => 8 [8] => 9

 // )

 

 

 $original = ['b', 'c', 'd'];

 $newArray = ['a', ...$original, 'e'];

 // Array (

 //   [0] => a [1] => b [2] => c [3] => d [4] => e

 // )

 

 

Function Arguments

 

 // FUNCTION ARGUMENTS

 function addNumbers($a, $b, $c) {

    return $a + $b + $c;

 }

 

 $numbers = [2, 4, 6];

 $result = addNumbers(...$numbers);

 echo $result; // Output: 12

 

 

 function sum(...$numbers) {

    return array_sum($numbers);

 }

 

 $values = [1, 2, 3, 4, 5];

 echo sum(...$values); // Output: 15

 

Combining With Regular Elements

 

 // Combining with Regular Elements

 $first = [1, 2];

 $last = [5, 6];

 $combined = [...$first, 3, 4, ...$last];

 print_r($combined);

 // Output: Array ([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6)

 

 

Usage With Associative Arrays

Notice that array keys are also considered making it perfect for merging associative arrays as well.  

 //With Associative Arrays

 $config1 = ['host' => 'localhost', 'port' => 3306];

 $config2 = ['username' => 'root', 'password' => 'secret'];

 

 $finalConfig = [...$config1, ...$config2];

 print_r($finalConfig);

// Output: Array ([host] => localhost [port] => 3306 [username] => root [password] => secret)

 

 

String To Array Conversion

 

 // String To Array Conversion

 $string = "hello";

 $chars = [...$string];

 print_r($chars);

 // Output: Array ([0] => h [1] => e [2] => l [3] => l [4] => o)

 

 

Practical Example of Merging 2 Configuration Arrays

Remember that when merging 2 associative arrays using the spread operator and brackets syntax, the second array in the will overwrite values with matching keys.  Take a look at the ‘debug’ key below:

 

 // Configuration Merging

 $defaultConfig = [

    'debug' => false,

    'cache' => true,

    'timeout' => 30

 ];

 

 $userConfig = [

    'debug' => true,

    'database' => 'mysql'

 ];

 

 $finalConfig = [...$defaultConfig, ...$userConfig];

 print_r($finalConfig);

 // Output: Array ([debug] => true [cache] => true [timeout] => 30 [database] => mysql)

 




PHP Null Coalescing Operator ??

0 👍
👎 0
 LAMP
The null coalescing operator ?? is used similar to the elvis operator ?:  In the example below the value of $var3 will only be the value of $var2 if $var1 is null.  With no value will $var3 be the value of $var1. 
 
Example 1:

$var1 = null;  // it's null
$var2 = 15;
$var3 = $var1 ?? $var2; // the value is 15

OR
$var1;  // it's undfefined
$var2 = 15;
$var3 = $var1 ?? $var2; // the value is 15

In Example 1 above the value of $var3 will be the value of $var2.  This is because value of $var1 is null or undefined.  If $var1 is any value besides null, the value of $var3 would be the value of $var1.  That case is displayed in Example 2 below.

In Example 2:

$var1 = 3;
$var2 = 15;
$var3 = $var1 ?? $var2;   // the value is 3

A Quick HowTo of PHP Operators

0 👍
👎 0
 LAMP

Math Operators

Addition:
Caculate the sum of two numbers using the + operator.

$sum = 1 + 3;
The value of $sum is 4.

Subtraction:
Caculate the difference of two numbers using the - operator.

$diff = 3 - 2;
The value of $diff is 1.

Division:
Calculate the quotient of two numbers using the / operator.

$quotient = 4 / 2;
The value of $quotient is 2.

Multiplication:
Calculate the product using the * operator.

$product = 4 * 5;
The value of $product is 20.

Modulo:
Gives the remainder after dividing two numbers the % operator.

$remainder = 10 % 3;
The value of $remainder is 1.

PHP Null Coalescing Assignment (??=)

0 👍
👎 0
 PHP

PHP Null-Coalescing Assignment (??=)

The PHP Null-Coalescing Assignment operator ??= is a shorthand that combines the null coalescing operator ?? with an assignment = operator.


Some benefits of the null coalescing assignment operator is it reduces code verbosity significantly. It’s readable with clear intent for setting defaults. It’s safe and avoids undefined variable notices. It’s efficient with a single operation instead of multiple lines.

Below is 3 different ways of accomplishing the same objective. The value of $variable will be 30. The first example uses the ??= (null-coalescing assignment) operator. Notice it's a shorthand for the other 2 similar methods:

 

 // Null-Coalescing Assignment (all-in-one)

 $variable ??= 30;

 

 // Null Coalescing combined with Assignment

 $variable = $variable ?? 30;

 

 // Ternary Operator combined with Assignment

 $variable = $variable ? $variable : 30;


Here are a few different ways of using the Null-Coalescing Assignment operator
??=

 

 // Variable is null

 $name = null;

 $name ??= 'Peter';

 echo $name; // Output: 'Peter'

 

 // Variable already has a value

 $count = 25;

 $count ??= 30;

 echo $count; // Output: 25 (unchanged)

 

 // Variable doesn't exist

 $location ??= 'Chicago';

 echo $location; // Output: 'Chicago'