05. String and Array Functions

05. String and Array Functions

String Functions

PHP provides a wide range of string functions that allow you to manipulate and process strings. Here are some commonly used string functions in PHP along with examples and challenging scenarios:

  1. strlen($string): Returns the length of a string.
$string = "Hello, world!";
$length = strlen($string);
echo $length;  // Output: 13
  1. str_replace($search, $replace, $string): Replaces all occurrences of a search string with a replacement string.
$string = "Hello, world!";
$newString = str_replace("world", "PHP", $string);
echo $newString;  // Output: Hello, PHP!
  1. strtoupper($string): Converts a string to uppercase.
$string = "hello, world!";
$upperString = strtoupper($string);
echo $upperString;  // Output: HELLO, WORLD!
  1. strtolower($string): Converts a string to lowercase.
$string = "HELLO, WORLD!";
$lowerString = strtolower($string);
echo $lowerString;  // Output: hello, world!
  1. substr($string, $start, $length): Returns a substring from a string.
$string = "Hello, world!";
$subString = substr($string, 0, 5);
echo $subString;  // Output: Hello
  1. strpos($string, $search): Returns the position of the first occurrence of a substring in a string.
$string = "Hello, world!";
$position = strpos($string, "world");
echo $position;  // Output: 7
  1. str_repeat($string, $multiplier): Repeats a string a specified number of times.
$string = "Hello!";
$repeatedString = str_repeat($string, 3);
echo $repeatedString;  // Output: Hello!Hello!Hello!
  1. trim($string): Removes whitespace or other characters from the beginning and end of a string.
$string = "  Hello, world!   ";
$trimmedString = trim($string);
echo $trimmedString;  // Output: Hello, world!
  1. addcslashes($string, $characters): Returns a string with backslashes in front of the specified characters.
$string = "Hello, world!";
$escapedString = addcslashes($string, 'e');
echo $escapedString;  // Output: H\ell\o, world!
  1. bin2hex($string): Converts a string of ASCII characters to hexadecimal values.
$string = "Hello, world!";
$hexString = bin2hex($string);
echo $hexString;  // Output: 48656c6c6f2c20776f726c6421
  1. chop($string, $characters): Removes whitespace or other characters from the right end of a string.
$string = "Hello, world!    ";
$trimmedString = chop($string);
echo $trimmedString;  // Output: Hello, world!
  1. chr($asciiValue): Returns a character from a specified ASCII value.
$asciiValue = 65;
$character = chr($asciiValue);
echo $character;  // Output: A
  1. chunk_split($string, $length, $end): Splits a string into a series of smaller parts.
$string = "Hello, world!";
$chunkedString = chunk_split($string, 2, "-");
echo $chunkedString;  // Output: He-ll-o,- w-or-ld-!
  1. count_chars($string, $mode): Returns information about characters used in a string.
$string = "Hello, world!";
$characterInfo = count_chars($string, 3);
print_r($characterInfo);
/*
Output:
Array
(
    [32] => 1
    [33] => 1
    [44] => 1
    [72] => 1
    [100] => 1
    [101] => 1
    [108] => 3
    [111] => 2
    [114] => 1
    [119] => 1
)
*/
  1. crc32($string): Calculates a 32-bit CRC for a string.
$string = "Hello, world!";
$crc32Value = crc32($string);
echo $crc32Value;  // Output: 222957957
  1. crypt($string, $salt): One-way string hashing.
$string = "password";
$salt = "somesalt";
$hashedString = crypt($string, $salt);
echo $hashedString;  // Output: somesalt/u4XpBbQ

These are just a few more examples of PHP string functions. You can explore the PHP documentation for each function to learn more about its parameters and usage.

List of Remaining string functions

addcslashes()

Returns a string with backslashes in front of the specified characters

addslashes()

Returns a string with backslashes in front of predefined characters

bin2hex()

Converts a string of ASCII characters to hexadecimal values

chop()

Removes whitespace or other characters from the right end of a string

chr()

Returns a character from a specified ASCII value

chunk_split()

Splits a string into a series of smaller parts

convert_cyr_string()

Converts a string from one Cyrillic character-set to another

convert_uudecode()

Decodes a uuencoded string

convert_uuencode()

Encodes a string using the uuencode algorithm

count_chars()

Returns information about characters used in a string

crc32()

Calculates a 32-bit CRC for a string

crypt()

One-way string hashing

echo()

Outputs one or more strings

explode()

Breaks a string into an array

fprintf()

Writes a formatted string to a specified output stream

get_html_translation_table()

Returns the translation table used by htmlspecialchars() and htmlentities()

hebrev()

Converts Hebrew text to visual text

hebrevc()

Converts Hebrew text to visual text and new lines (\n) into <br>

hex2bin()

Converts a string of hexadecimal values to ASCII characters

html_entity_decode()

Converts HTML entities to characters

htmlentities()

Converts characters to HTML entities

htmlspecialchars_decode()

Converts some predefined HTML entities to characters

htmlspecialchars()

Converts some predefined characters to HTML entities

implode()

Returns a string from the elements of an array

join()

Alias of implode()

lcfirst()

Converts the first character of a string to lowercase

levenshtein()

Returns the Levenshtein distance between two strings

localeconv()

Returns locale numeric and monetary formatting information

ltrim()

Removes whitespace or other characters from the left side of a string

md5()

Calculates the MD5 hash of a string

md5_file()

Calculates the MD5 hash of a file

metaphone()

Calculates the metaphone key of a string

money_format()

Returns a string formatted as a currency string

nl_langinfo()

Returns specific local information

nl2br()

Inserts HTML line breaks in front of each newline in a string

number_format()

Formats a number with grouped thousands

ord()

Returns the ASCII value of the first character of a string

parse_str()

Parses a query string into variables

print()

Outputs one or more strings

printf()

Outputs a formatted string

quoted_printable_decode()

Converts a quoted-printable string to an 8-bit string

quoted_printable_encode()

Converts an 8-bit string to a quoted printable string

quotemeta()

Quotes meta characters

rtrim()

Removes whitespace or other characters from the right side of a string

setlocale()

Sets locale information

sha1()

Calculates the SHA-1 hash of a string

sha1_file()

Calculates the SHA-1 hash of a file

similar_text()

Calculates the similarity between two strings

soundex()

Calculates the soundex key of a string

sprintf()

Writes a formatted string to a variable

sscanf()

Parses input from a string according to a format

str_getcsv()

Parses a CSV string into an array

str_ireplace()

Replaces some characters in a string (case-insensitive)

str_pad()

Pads a string to a new length

str_repeat()

Repeats a string a specified number of times

str_replace()

Replaces some characters in a string (case-sensitive)

str_rot13()

Performs the ROT13 encoding on a string

str_shuffle()

Randomly shuffles all characters in a string

str_split()

Splits a string into an array

str_word_count()

Count the number of words in a string

strcasecmp()

Compares two strings (case-insensitive)

strchr()

Finds the first occurrence of a string inside another string (alias of strstr())

strcmp()

Compares two strings (case-sensitive)

strcoll()

Compares two strings (locale based string comparison)

strcspn()

Returns the number of characters found in a string before any part of some specified characters are found

strip_tags()

Strips HTML and PHP tags from a string

stripcslashes()

Unquotes a string quoted with addcslashes()

stripslashes()

Unquotes a string quoted with addslashes()

stripos()

Returns the position of the first occurrence of a string inside another string (case-insensitive)

stristr()

Finds the first occurrence of a string inside another string (case-insensitive)

strlen()

Returns the length of a string

strnatcasecmp()

Compares two strings using a "natural order" algorithm (case-insensitive)

strnatcmp()

Compares two strings using a "natural order" algorithm (case-sensitive)

strncasecmp()

String comparison of the first n characters (case-insensitive)

strncmp()

String comparison of the first n characters (case-sensitive)

strpbrk()

Searches a string for any of a set of characters

strpos()

Returns the position of the first occurrence of a string inside another string (case-sensitive)

strrchr()

Finds the last occurrence of a string inside another string

strrev()

Reverses a string

strripos()

Finds the position of the last occurrence of a string inside another string (case-insensitive)

strrpos()

Finds the position of the last occurrence of a string inside another string (case-sensitive)

strspn()

Returns the number of characters found in a string that contains only characters from a specified charlist

strstr()

Finds the first occurrence of a string inside another string (case-sensitive)

strtok()

Splits a string into smaller strings

strtolower()

Converts a string to lowercase letters

strtoupper()

Converts a string to uppercase letters

strtr()

Translates certain characters in a string

substr()

Returns a part of a string

substr_compare()

Compares two strings from a specified start position (binary safe and optionally case-sensitive)

substr_count()

Counts the number of times a substring occurs in a string

substr_replace()

Replaces a part of a string with another string

trim()

Removes whitespace or other characters from both sides of a string

ucfirst()

Converts the first character of a string to uppercase

ucwords()

Converts the first character of each word in a string to uppercase

vfprintf()

Writes a formatted string to a specified output stream

vprintf()

Outputs a formatted string

vsprintf()

Writes a formatted string to a variable

wordwrap()

Wraps a string to a given number of characters

Here's a comprehensive list of the PHP string functions along with examples and explanations for each:

  1. addcslashes($string, $characters):

    • Example:

        $string = "Hello, world!";
        $escapedString = addcslashes($string, 'e');
        echo $escapedString;  // Output: H\ell\o, world!
      
    • Explanation: The addcslashes() function adds a backslash before each specified character in a string.

  2. addslashes($string):

    • Example:

        $string = "It's a beautiful day!";
        $escapedString = addslashes($string);
        echo $escapedString;  // Output: It\'s a beautiful day!
      
    • Explanation: The addslashes() function adds a backslash before predefined characters (\, ', ", and NUL) in a string.

  3. bin2hex($string):

    • Example:

        $string = "Hello, world!";
        $hexString = bin2hex($string);
        echo $hexString;  // Output: 48656c6c6f2c20776f726c6421
      
    • Explanation: The bin2hex() function converts a string of ASCII characters to hexadecimal values.

  4. chop($string, $characters):

    • Example:

        $string = "Hello, world!    ";
        $trimmedString = chop($string);
        echo $trimmedString;  // Output: Hello, world!
      
    • Explanation: The chop() function removes whitespace or specified characters from the right end of a string.

  5. chr($asciiValue):

    • Example:

        $asciiValue = 65;
        $character = chr($asciiValue);
        echo $character;  // Output: A
      
    • Explanation: The chr() function returns a character from a specified ASCII value.

  6. chunk_split($string, $length, $end):

    • Example:

        $string = "Hello, world!";
        $chunkedString = chunk_split($string, 2, "-");
        echo $chunkedString;  // Output: He-ll-o,- w-or-ld-!
      
    • Explanation: The chunk_split() function splits a string into smaller parts with a specified length and adds a separator at the end of each part.

  7. convert_cyr_string($string, $from, $to):

    • Example:

        $string = "Привет, мир!";
        $convertedString = convert_cyr_string($string, "w", "k");
        echo $convertedString;  // Output: Привет, мир!
      
    • Explanation: The convert_cyr_string() function converts a string from one Cyrillic character set to another.

  8. convert_uudecode($string):

    • Example:

        $string = "=:T$9R;V]T=\"!U8@=V]R:6YT96YT<R]T:&5R";
        $decodedString = convert_uudecode($string);
        echo $decodedString;  // Output: OpenAI is amazing!
      
    • Explanation: The convert_uudecode() function decodes a uuencoded string.

  9. convert_uuencode($string):

    • Example:

        $string = "OpenAI is amazing!";
        $encodedString = convert_uuencode($string);
        echo $encodedString
      

; /* Output: begin 644 encoded.txt M5&AE('-T<F]O9!S:&]C=#P@,"!R;W!E;@`` end */ ```

  • Explanation: The convert_uuencode() function encodes a string using the uuencode algorithm.
  1. count_chars($string, $mode):

    • Example:

        $string = "Hello, world!";
        $characterInfo = count_chars($string, 3);
        print_r($characterInfo);
        /*
        Output:
        Array
        (
            [32] => 1
            [33] => 1
            [44] => 1
            [72] => 1
            [100] => 1
            [101] => 1
            [108] => 3
            [111] => 2
            [114] => 1
            [119] => 1
        )
        */
      
    • Explanation: The count_chars() function returns information about characters used in a string. The $mode parameter determines the type of information returned.

  2. crc32($string):

    • Example:

        $string = "Hello, world!";
        $crc32Value = crc32($string);
        echo $crc32Value;  // Output: 222957957
      
    • Explanation: The crc32() function calculates a 32-bit CRC (Cyclic Redundancy Check) for a string.

  3. crypt($string, $salt):

    • Example:

        $string = "password";
        $salt = "somesalt";
        $hashedString = crypt($string, $salt);
        echo $hashedString;  // Output: somesalt/u4XpBbQ
      
    • Explanation: The crypt() function performs a one-way string hashing using the DES, Blowfish, or MD5 algorithm.

  4. echo($string1, $string2, ...):

    • Example:

        $string1 = "Hello";
        $string2 = "world!";
        echo $string1, " ", $string2;  // Output: Hello world!
      
    • Explanation: The echo() function outputs one or more strings.

  5. explode($delimiter, $string, $limit = PHP_INT_MAX):

    • Example:

        $string = "Hello,world,how,are,you?";
        $parts = explode(",", $string);
        print_r($parts);
        /*
        Output:
        Array
        (
            [0] => Hello
            [1] => world
            [2] => how
            [3] => are
            [4] => you?
        )
        */
      
    • Explanation: The explode() function breaks a string into an array of substrings based on a specified delimiter.

  6. fprintf($handle, $format, $arg1, $arg2, ...):

    • Example:

        $file = fopen("output.txt", "w");
        $string = "Hello, world!";
        fprintf($file, "Message: %s", $string);
        fclose($file);
      
    • Explanation: The fprintf() function writes a formatted string to a specified output stream.

  7. get_html_translation_table($table = HTML_SPECIALCHARS, $flags = ENT_COMPAT | ENT_HTML401, $encoding = "UTF-8"):

    • Example:

        $translationTable = get_html_translation
      

table(HTMLENTITIES); print_r($translationTable); /* Output: Array ( [&] => & [<] => < [>] => > ["] => " ['] => ' ) */ ``` - Explanation: The get_html_translation_table() function returns the translation table used by htmlspecialchars() and htmlentities().

  1. hebrev($string, $maxCharsPerLine = 0):

    • Example:

        $string = "שלום, עולם!";
        $hebrewString = hebrev($string);
        echo $hebrewString;  // Output: םולע ,םולש
      
    • Explanation: The hebrev() function converts Hebrew text to visual text, which is suitable for display purposes.

  2. hebrevc($string, $maxCharsPerLine = 0):

    • Example:

        $string = "שלום, עולם!\nכיף לראותכם!";
        $hebrewString = hebrevc($string);
        echo $hebrewString;
        /*
        Output:
        םולע ,םולש
        !מכאשמ לתוארכ
        */
      
    • Explanation: The hebrevc() function converts Hebrew text to visual text, preserves newlines (\n), and replaces them with <br> tags.

  3. hex2bin($hexString):

    • Example:

        $hexString = "48656c6c6f2c20776f726c6421";
        $string = hex2bin($hexString);
        echo $string;  // Output: Hello, world!
      
    • Explanation: The hex2bin() function converts a string of hexadecimal values to ASCII characters.

  4. html_entity_decode($string, $flags = ENT_COMPAT | ENT_HTML401, $encoding = "UTF-8"):

    • Example:

        $string = "&lt;p&gt;Hello, world!&lt;/p&gt;";
        $decodedString = html_entity_decode($string);
        echo $decodedString;  // Output: <p>Hello, world!</p>
      
    • Explanation: The html_entity_decode() function converts HTML entities to characters.

Please note that the list continues with more string functions. If you would like to continue with the next set of functions, please let me know.

Array Functions

Sure! Here are the descriptions, examples, and explanations of the PHP array functions you listed:

  1. array(): Creates an array.

    • Example:

        $array = array("apple", "banana", "orange");
      
    • Explanation: The array() function creates an array with the specified elements.

  2. array_change_key_case(): Changes all keys in an array to lowercase or uppercase.

    • Example:

        $array = array("name" => "John", "age" => 30);
        $lowercaseArray = array_change_key_case($array, CASE_LOWER);
        print_r($lowercaseArray);
        /*
        Output:
        Array
        (
            [name] => John
            [age] => 30
        )
        */
      
    • Explanation: The array_change_key_case() function returns an array with all keys either in lowercase or uppercase.

  3. array_chunk(): Splits an array into chunks of arrays.

    • Example:

        $array = array("apple", "banana", "orange", "cherry", "grape");
        $chunks = array_chunk($array, 2);
        print_r($chunks);
        /*
        Output:
        Array
        (
            [0] => Array
                (
                    [0] => apple
                    [1] => banana
                )
      
            [1] => Array
                (
                    [0] => orange
                    [1] => cherry
                )
      
            [2] => Array
                (
                    [0] => grape
                )
      
        )
        */
      
    • Explanation: The array_chunk() function splits an array into chunks of specified size, and returns a multidimensional array.

  4. array_column(): Returns the values from a single column in the input array.

    • Example:

        $people = array(
            array("name" => "John", "age" => 30),
            array("name" => "Jane", "age" => 25),
            array("name" => "Bob", "age" => 40)
        );
        $names = array_column($people, "name");
        print_r($names);
        /*
        Output:
        Array
        (
            [0] => John
            [1] => Jane
            [2] => Bob
        )
        */
      
    • Explanation: The array_column() function returns the values from a single column of the input array.

  5. array_combine(): Creates an array by using the elements from one "keys" array and one "values" array.

    • Example:

        $keys = array("name", "age", "city");
        $values = array("John", 30, "New York");
        $combinedArray = array_combine($keys, $values);
        print_r($combinedArray);
        /*
        Output:
        Array
        (
            [name] => John
            [age] => 30
            [city] => New York
        )
        */
      
    • Explanation: The array_combine() function creates an array using the elements from one array as keys and the elements from another array as values.

  6. array_count_values(): Counts all the values of an array.

    • Example:

        $array = array("apple", "banana", "apple", "cherry", "banana");
        $valueCounts = array_count_values($array);
        print_r($valueCounts);
        /*
        Output:
        Array
        (
            [apple] => 2
            [banana] => 2
      

[cherry] => 1 ) */ ```

  • Explanation: The array_count_values() function counts the occurrences of each value in an array and returns an associative array with the values as keys and their counts as values.
  1. array_diff(): Compares arrays and returns the differences (compare values only).

    • Example:

        $array1 = array("apple", "banana", "orange");
        $array2 = array("banana", "cherry");
        $diff = array_diff($array1, $array2);
        print_r($diff);
        /*
        Output:
        Array
        (
            [0] => apple
            [2] => orange
        )
        */
      
    • Explanation: The array_diff() function compares arrays and returns the values from the first array that are not present in any of the other arrays.

  2. array_diff_assoc(): Compares arrays and returns the differences (compare keys and values).

    • Example:

        $array1 = array("a" => "apple", "b" => "banana", "c" => "orange");
        $array2 = array("a" => "banana", "b" => "cherry");
        $diff = array_diff_assoc($array1, $array2);
        print_r($diff);
        /*
        Output:
        Array
        (
            [a] => apple
            [c] => orange
        )
        */
      
    • Explanation: The array_diff_assoc() function compares arrays and returns the key-value pairs from the first array that are not present in any of the other arrays, considering both keys and values.

  3. array_diff_key(): Compares arrays and returns the differences (compare keys only).

    • Example:

        $array1 = array("a" => "apple", "b" => "banana", "c" => "orange");
        $array2 = array("b" => "banana", "c" => "cherry");
        $diff = array_diff_key($array1, $array2);
        print_r($diff);
        /*
        Output:
        Array
        (
            [a] => apple
        )
        */
      
    • Explanation: The array_diff_key() function compares arrays and returns the key-value pairs from the first array that have keys not present in any of the other arrays.

  4. array_diff_uassoc(): Compares arrays and returns the differences (compare keys and values, using a user-defined key comparison function).

    • Example:

        $array1 = array("a" => "apple", "b" => "banana", "c" => "orange");
        $array2 = array("a" => "banana", "b" => "cherry");
        $diff = array_diff_uassoc($array1, $array2, "key_compare_func");
        print_r($diff);
        /*
        Output:
        Array
        (
            [a] => apple
            [c] => orange
        )
        */
      
    • Explanation: The array_diff_uassoc() function compares arrays and returns the key-value pairs from the first array that are not present in any of the other arrays, using a user-defined function for comparing keys.

  5. array_diff_ukey(): Compares arrays and returns the differences (compare keys only, using a user-defined key comparison function).

    • Example:

        $array1 = array("a" => "apple", "b" => "banana", "c" => "orange");
        $array2 = array("b" => "banana",
      

"c" => "cherry"); $diff = array_diff_ukey($array1, $array2, "key_compare_func"); print_r($diff); /* Output: Array ( [a] => apple ) */ ``` - Explanation: The array_diff_ukey() function compares arrays and returns the key-value pairs from the first array that have keys not present in any of the other arrays, using a user-defined function for comparing keys.

  1. array_fill(): Fills an array with values.
  • Example:
$filledArray = array_fill(0, 5, 'value');
print_r($filledArray);
/*
Output:
Array
(
    [0] => value
    [1] => value
    [2] => value
    [3] => value
    [4] => value
)
*/
  • Explanation: The array_fill() function creates an array with a specified number of elements, filled with a specified value.
  1. array_fill_keys(): Fills an array with values, specifying keys.
  • Example:
$keys = array('a', 'b', 'c');
$filledArray = array_fill_keys($keys, 'value');
print_r($filledArray);
/*
Output:
Array
(
    [a] => value
    [b] => value
    [c] => value
)
*/
  • Explanation: The array_fill_keys() function creates an array with the specified keys and fills it with a specified value.
  1. array_filter(): Filters the values of an array using a callback function.
  • Example:
$numbers = array(1, 2, 3, 4, 5);
$filteredArray = array_filter($numbers, function($value) {
    return $value % 2 == 0; // Filter even numbers
});
print_r($filteredArray);
/*
Output:
Array
(
    [1] => 2
    [3] => 4
)
*/
  • Explanation: The array_filter() function filters the elements of an array based on a callback function and returns the filtered array.
  1. array_flip(): Flips/exchanges all keys with their associated values in an array.
  • Example:
$originalArray = array('a' => 1, 'b' => 2, 'c' => 3);
$flippedArray = array_flip($originalArray);
print_r($flippedArray);
/*
Output:
Array
(
    [1] => a
    [2] => b
    [3] => c
)
*/
  • Explanation: The array_flip() function exchanges all keys with their associated values in an array.
  1. array_intersect(): Compares arrays and returns the matches (compare values only).
  • Example:
$array1 = array(1, 2, 3, 4);
$array2 = array(3, 4, 5, 6);
$intersectedArray = array_intersect($array1, $array2);
print_r($intersectedArray);
/*
Output:
Array
(
    [2] => 3
    [3] => 4
)
*/
  • Explanation: The array_intersect() function compares arrays and returns the values that are present in all arrays.
  1. array_intersect_assoc(): Compares arrays and returns the matches (compare keys and values).
  • Example:
$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('b' => 2, 'c' => 3, 'd' => 4);
$intersectedArray = array_intersect_assoc($array1, $array2);
print

_r($intersectedArray);
/*
Output:
Array
(
    [b] => 2
    [c] => 3
)
*/
  • Explanation: The array_intersect_assoc() function compares arrays and returns the key-value pairs that are present in all arrays.
  1. array_intersect_key(): Compares arrays and returns the matches (compare keys only).
  • Example:
$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('b' => 20, 'c' => 30, 'd' => 40);
$intersectedArray = array_intersect_key($array1, $array2);
print_r($intersectedArray);
/*
Output:
Array
(
    [b] => 2
    [c] => 3
)
*/
  • Explanation: The array_intersect_key() function compares arrays and returns the key-value pairs that have keys present in all arrays.
  1. array_intersect_uassoc(): Compares arrays and returns the matches (compare keys and values, using a user-defined key comparison function).
  • Example:
$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('b' => 20, 'c' => 30, 'd' => 40);
$intersectedArray = array_intersect_uassoc($array1, $array2, 'key_compare_func');
print_r($intersectedArray);
/*
Output:
Array
(
    [b] => 2
)
*/
  • Explanation: The array_intersect_uassoc() function compares arrays and returns the key-value pairs that have keys and values present in all arrays, using a user-defined key comparison function.
  1. array_intersect_ukey(): Compares arrays and returns the matches (compare keys only, using a user-defined key comparison function).
  • Example:
$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('b' => 20, 'c' => 30, 'd' => 40);
$intersectedArray = array_intersect_ukey($array1, $array2, 'key_compare_func');
print_r($intersectedArray);
/*
Output:
Array
(
    [b] => 2
    [c] => 3
)
*/
  • Explanation: The array_intersect_ukey() function compares arrays and returns the key-value pairs that have keys present in all arrays, using a user-defined key comparison function.
  1. array_key_exists(): Checks if the specified key exists in the array.
  • Example:
$array = array('a' => 1, 'b' => 2, 'c' => 3);
if (array_key_exists('b', $array)) {
    echo "Key 'b' exists in the array.";
} else {
    echo "Key 'b' does not exist in the array.";
}
/*
Output:
Key 'b' exists in the array.
*/
  • Explanation: The array_key_exists() function checks if a specified key exists in the array.
  1. array_keys(): Returns all the keys of an array.
  • Example:
$array = array('a' => 1, 'b' => 2, 'c' => 3);
$keys = array_keys($array);
print_r($keys);
/*
Output:
Array
(
    [0] => a
    [1] => b
    [2] => c
)
*/
  • Explanation: The array_keys() function returns an array containing all the keys of the input array.
  1. array_map(): Applies a user-made function to each element of an array and returns a new array with the modified values.
  • Example:
$numbers = array(1, 2, 3, 4, 5);
$squaredNumbers = array_map(function($value) {
    return $value * $value;
}, $numbers);
print_r($squaredNumbers);
/*
Output:
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)
*/
  • Explanation: The array_map() function applies a user-defined function to each element of the input array and returns a new array with the modified values.
  1. array_merge(): Merges two or more arrays into a single array.
  • Example:
$array1 = array('a', 'b', 'c');
$array2 = array(1, 2, 3);
$mergedArray = array_merge($array1, $array2);
print_r($mergedArray);
/*
Output:
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => 1
    [4] => 2
    [5] => 3
)
*/
  • Explanation: The array_merge() function merges two or more arrays into a single array.
  1. array_merge_recursive(): Recursively merges two or more arrays into a single array.
  • Example:
$array1 = array('a' => 1, 'b' => 2);
$array2 = array('a' => 10, 'c' => 3);
$mergedArray = array_merge_recursive($array1, $array2);
print_r($mergedArray);
/*
Output:
Array
(
    [a] => Array
        (
            [0] => 1
            [1] => 10
        )
    [b] => 2
    [c] => 3
)
*/
  • Explanation: The array_merge_recursive() function recursively merges two or more arrays into a

single array, combining elements with the same keys into arrays.

  1. array_multisort(): Sorts multiple or multidimensional arrays simultaneously.
  • Example:
$array1 = array(4, 2, 5);
$array2 = array('a', 'b', 'c');
array_multisort($array1, $array2);
print_r($array1);
print_r($array2);
/*
Output:
Array
(
    [0] => 2
    [1] => 4
    [2] => 5
)
Array
(
    [0] => b
    [1] => a
    [2] => c
)
*/
  • Explanation: The array_multisort() function sorts multiple or multidimensional arrays simultaneously based on one or more sort criteria.
  1. array_pad(): Inserts a specified number of elements, with a specified value, to the beginning or end of an array.
  • Example:
$array = array('a', 'b');
$paddedArray = array_pad($array, 5, 'c');
print_r($paddedArray);
/*
Output:
Array
(
    [0] => c
    [1] => c
    [2] => a
    [3] => b
    [4] => c
)
*/
  • Explanation: The array_pad() function inserts a specified number of elements with a specified value to the beginning or end of an array, resulting in a new array.
  1. array_pop(): Removes and returns the last element of an array.
  • Example:
$array = array('a', 'b', 'c');
$lastElement = array_pop($array);
echo $lastElement;  // Output: c
print_r($array);
/*
Output:
Array
(
    [0] => a
    [1] => b
)
*/
  • Explanation: The array_pop() function removes and returns the last element of an array.
  1. array_product(): Calculates the product of the values in an array.
  • Example:
$array = array(2, 4, 6);
$product = array_product($array);
echo $product;  // Output: 48 (2 * 4 * 6)
  • Explanation: The array_product() function calculates the product of the values in an array.
  1. array_push(): Inserts one or more elements to the end of an array.
  • Example:
$array = array('a', 'b');
array_push($array, 'c', 'd');
print_r($array);
/*
Output:
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)
*/
  • Explanation: The array_push() function inserts one or more elements to the end of an array.

These are the remaining PHP array functions. If you have any specific function you'd like more explanation or examples for, feel free to let me know!

array()

Creates an array

array_change_key_case()

Changes all keys in an array to lowercase or uppercase

array_chunk()

Splits an array into chunks of arrays

array_column()

Returns the values from a single column in the input array

array_combine()

Creates an array by using the elements from one "keys" array and one "values" array

array_count_values()

Counts all the values of an array

array_diff()

Compare arrays, and returns the differences (compare values only)

array_diff_assoc()

Compare arrays, and returns the differences (compare keys and values)

array_diff_key()

Compare arrays, and returns the differences (compare keys only)

array_diff_uassoc()

Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function)

array_diff_ukey()

Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function)

array_fill()

Fills an array with values

array_fill_keys()

Fills an array with values, specifying keys

array_filter()

Filters the values of an array using a callback function

array_flip()

Flips/Exchanges all keys with their associated values in an array

array_intersect()

Compare arrays, and returns the matches (compare values only)

array_intersect_assoc()

Compare arrays and returns the matches (compare keys and values)

array_intersect_key()

Compare arrays, and returns the matches (compare keys only)

array_intersect_uassoc()

Compare arrays, and returns the matches (compare keys and values, using a user-defined key comparison function)

array_intersect_ukey()

Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function)

array_key_exists()

Checks if the specified key exists in the array

array_keys()

Returns all the keys of an array

array_map()

Sends each value of an array to a user-made function, which returns new values

array_merge()

Merges one or more arrays into one array

array_merge_recursive()

Merges one or more arrays into one array recursively

array_multisort()

Sorts multiple or multi-dimensional arrays

array_pad()

Inserts a specified number of items, with a specified value, to an array

array_pop()

Deletes the last element of an array

array_product()

Calculates the product of the values in an array

array_push()

Inserts one or more elements to the end of an array

array_rand()

Returns one or more random keys from an array

array_reduce()

Returns an array as a string, using a user-defined function

array_replace()

Replaces the values of the first array with the values from following arrays

array_replace_recursive()

Replaces the values of the first array with the values from following arrays recursively

array_reverse()

Returns an array in the reverse order

array_search()

Searches an array for a given value and returns the key

array_shift()

Removes the first element from an array, and returns the value of the removed element

array_slice()

Returns selected parts of an array

array_splice()

Removes and replaces specified elements of an array

array_sum()

Returns the sum of the values in an array

array_udiff()

Compare arrays, and returns the differences (compare values only, using a user-defined key comparison function)

array_udiff_assoc()

Compare arrays, and returns the differences (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)

array_udiff_uassoc()

Compare arrays, and returns the differences (compare keys and values, using two user-defined key comparison functions)

array_uintersect()

Compare arrays, and returns the matches (compare values only, using a user-defined key comparison function)

array_uintersect_assoc()

Compare arrays, and returns the matches (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)

array_uintersect_uassoc()

Compare arrays, and returns the matches (compare keys and values, using two user-defined key comparison functions)

array_unique()

Removes duplicate values from an array

array_unshift()

Adds one or more elements to the beginning of an array

array_values()

Returns all the values of an array

array_walk()

Applies a user function to every member of an array

array_walk_recursive()

Applies a user function recursively to every member of an array

arsort()

Sorts an associative array in descending order, according to the value

asort()

Sorts an associative array in ascending order, according to the value

compact()

Create array containing variables and their values

count()

Returns the number of elements in an array

current()

Returns the current element in an array

each()

Deprecated from PHP 7.2. Returns the current key and value pair from an array

end()

Sets the internal pointer of an array to its last element

extract()

Imports variables into the current symbol table from an array

in_array()

Checks if a specified value exists in an array

key()

Fetches a key from an array

krsort()

Sorts an associative array in descending order, according to the key

ksort()

Sorts an associative array in ascending order, according to the key

list()

Assigns variables as if they were an array

natcasesort()

Sorts an array using a case insensitive "natural order" algorithm

natsort()

Sorts an array using a "natural order" algorithm

next()

Advance the internal array pointer of an array

pos()

Alias of current()

prev()

Rewinds the internal array pointer

range()

Creates an array containing a range of elements

reset()

Sets the internal pointer of an array to its first element

rsort()

Sorts an indexed array in descending order

shuffle()

Shuffles an array

sizeof()

Alias of count()

sort()

Sorts an indexed array in ascending order

uasort()

Sorts an array by values using a user-defined comparison function and maintains the index association

uksort()

Sorts an array by keys using a user-defined comparison function

usort()

Sorts an array by values using a user-defined comparison function