Aware about Important PHP Built In functions that we need to use always

php built in functions
Fetch the values of keys from an array.

Use array_column() function.

eg: I need all the id from the below array:

$data = [ [‘id’ => 1, ‘name’ => ‘Alice’, ‘age’ => 25], [‘id’ => 2, ‘name’ => ‘Bob’, ‘age’ => 30], [‘id’ => 3, ‘name’ => ‘Charlie’, ‘age’ => 35] ];

$names = array_column($data, ‘id’);

————— output———–
Array ( [0] => 1 [1] => 2 [2] => 3 )

$arr = [1, 2, 3];

echo is_array($arr); // Output: 1 (true)

 This function combines the elements of all input arrays and returns a new array containing all the elements.

array_merge(array $array1, array$arrays): array

Eg:

$array1 = [1, 2, 3];

$array2 = [4, 5, 6];

$merged = array_merge($array1, $array2);

print_r($merged);

———— Result———-

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

  • strlen($string) : Returns the length of a string. 

      echo strlen(“Hello World”); 

  • str_replace($search, $replace, $subject): Replaces all occurrences of a substring with a replacement.

    echo str_replace(“world”, “PHP”, “Hello world”)
  • substr($string, $start, $length): Returns a part of a string.
    echo substr(“Hello World”, 6, 5); // Output: World
  • strpos($haystack, $needle): Finds the position of the first occurrence of a substring.

    echo strpos(“Hello World”, “World”); // Output: 6

  • ucwords($string): Capitalizes the first letter of each word in a string.

    echo ucwords(“hello world”); // Output: Hello World

  • array_push($array, $value): Adds one or more elements to the end of an array.

    $arr = [1, 2, 3]; array_push($arr, 4); // $arr = [1, 2, 3, 4]

  • array_pop($array): Removes the last element from an array.
    array_pop($arr); // $arr = [1, 2, 3]
  • array_map($callback, $array): Applies a function to each element in the array.

    $arr = [1, 2, 3]; $squared = array_map(function($n) { return $n * $n; }, $arr); // $squared = [1, 4, 9]

  • array_filter($array, $callback): Filters elements of an array using a callback.

    $arr = [1, 2, 3, 4];
    $even = array_filter($arr, function($n) { return $n % 2 === 0; }); // $even = [2, 4]
  • abs($number): Returns the absolute value of a number.
    echo abs(-5); // Output: 5
  • round($number, $precision): Rounds a number to a specified precision.
    echo round(3.14159, 2); // Output: 3.14
  • min($value1, $value2, ...): Returns the smallest value from a set of values.
    echo min(1, 2, 3); // Output: 1

  • max($value1, $value2, ...): Returns the largest value from a set of values.
    echo max(1, 2, 3); // Output: 3

  • rand($min, $max): Generates a random integer between the two numbers.
    echo rand(1, 100); // Output: Random number between 1 and 100

Leave a Reply

Your email address will not be published. Required fields are marked *