Skip to content

Instantly share code, notes, and snippets.

@taniarascia
Created September 23, 2018 03:36
Show Gist options
  • Save taniarascia/5db866772cf7935570e2e5d2599bea89 to your computer and use it in GitHub Desktop.
Save taniarascia/5db866772cf7935570e2e5d2599bea89 to your computer and use it in GitHub Desktop.
PHP functions

PHP Functions

Display PHP errors

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Capitalize first letter

ucfirst('hello world');

// hello world -> Hello world

Capitalize all words

ucwords('hello world');

// hello world -> Hello World

Replace values in string

str_replace('-', ' ', 'hello-world');

// hello-world -> hello world

Find index of first value in a string

strpos('hello world', 'hello');

// 0

Make a string lowercase

strtolower('HELLO world');

// HELLO world -> hello world

Make a string uppercase

strtoupper('HELLO world');

// HELLO world -> HELLO WORLD

Comma separate values in an array

$arr = [1, 2, 3];

foreach ($arr as $value) {
    $comma_separated = (!empty($comma_separated)) 
    ? $comma_separated .= ', ' . $value 
    : $comma_separated = $value; 
}

// $comma_separated -> "1, 2, 3" (string)

Create an array from a string

$arr = 'one two three';
$each = explode(' ', $arr);

// $each[0] -> 'one'

Push to an array

foreach ($arr as $value) {
  $newArray[] = [
    'id'   => $value['id'],
    'name' => $value['name'],
  ];
}

Create comma separated strings from array

$arr = [1, 2, 3];

foreach ($arr as $val) {
    $newarr .= $prefix . "'". $val . "'";
    $prefix = ', ';
}
// '1', '2', '3'

echo $newarr;

Get duplicate values from an array

function get_duplicates( $array ) {
    return array_unique( array_diff_assoc( $array, array_unique( $array ) ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment