concatenate string and variable in php code example

Example 1: how to combine variables and text into a string php

<?php
$number = 8;
$txt = "the number is".$number.", ok?"; //Use a dot to combine
echo $txt;
?>

Example 2: php concat variable and string

<?php
  $name = "Paul";	
  $age = 26;

  echo "My name is {$name}, I'm {$age} years old ";

Example 3: append variable into string php

echo "'$animal'";

Example 4: php concatenate variables to function

public function getAvg(string $var) {
  # A sample from a game I wrote.
  # Concatenatin on the other side is just {stuff.$var}
  # You can also concatenate multiple variables in a varaible:
  # {$varA.$varb}
  $min = $this->{$var._min};
  # Assigns to $min object property matching $var + '_min' string.
  $max = $this->{$var._max};
  # Assigns to $max object property matching $var + '_max' string.
  $avg = (($min + $max) / 2);
  return round($avg);
}

Tags:

Php Example