Manipulating the string as an array in PHP

 Manipulating the string as an array in PHP

  • PHP provides various in-built methods to convert a string to an array.

Following are the methods for converting a string to an array.

1.    str_split() Function

2.    explode("DELIMITER", STRING)

3.    preg_split() Function

4.    str_word_count() Function

5.    Manually loop through the string

 

1. str_split() Function

  • An in-built PHP method is used to convert a string into an array by breaking the string into smaller sub-strings of uniform length and storing them in an array.
  • Do not use any kind of separator, just splits the string.

 syntax:

str_split($initial_string, $splitting_length)

 Parameters

·         $initial_string (mandatory): first parameter, a string that has to be converted into an array.

·         $splitting_length (optional): second parameter, an integer that represents how long the parts of the strings will be splitting. an optional parameter. If not passed, the function will consider this length as 1 by default.

  •  This function returns an array that contains the pieces of the original string.
  • If the length is passed to the function of the initial string, the function will return the whole string as one element.
  • If the length integer is less than one, the function will return false.

 Example

<?php

    // define a string

    $my_string = 'Sample String';   

    // without passing length

    // length = 1 (by default)

    $my_array1 = str_split($my_string);

    // print the array

    echo "The array of default length elements is: ";

    print_r($my_array1); // s, a, m, p, l, e, s, t, r, i, n, g

    print("<br><br>");   

    // passing length as second argument

    // length = 3

    $my_array2 = str_split($my_string, 3);

    // print the array

    echo "The array of length 3 elements is: ";

    print_r($my_array2); // sam, ple, str, ing 

?>



2.  explode("DELIMITER", STRING)

  • Returns an array that contains the string pieces as its elements Use a separator or delimiter. (separator:- comma (,), a dot (.), or anything).
  • After splitting the string into smaller substrings, this function stores them in an array and returns the array.

 syntax:-

explode($separator, $initial_string, $no_of_elements)

Parameters

·         $separator: a character that split the string to the separator and stores that substring in the array.

·         $initial_name: a string that has to be converted into an array.

·         $no_of_elements (optional): the number of strings in which it should split the original string. This number can be positive, negative, or zero.

·         Positive: If the integer is positive, then the array will store many numbers of elements.

·         Zero: If the integer is 0, then the array will contain the whole string as a single element.

·         Negative: If the integer is negative then the last N elements of the array will be cut off and it will return the remaining elements. 

Example

example :- explode() function to convert string to array in PHP.

<?php

    // define a string

    $my_string = 'red, green, blue';    

    // passing "," as the delimiter

    $my_array1 = explode(",", $my_string);

    // print the array

    echo "The converted Sarray is: <br>";

    print_r($my_array1); // red, green, blue 

?>


 

3.  preg_split() Function

  • Returns an array containing the substrings as its elements, separated by the pattern passed to the function.
  • Used to convert a string into an array by splitting it into smaller substrings.
  • Uses a separator but the separator in this function is a pattern of regular expressions.
  • The length of substrings depends upon the integer value known as a limit that is passed to this function.

 Syntax:

preg_split($pattern, $string, $limit, $flags)

Parameters

·         $pattern: a regular expression that determines what character is used as a separator to split the string.

·         $string: the string that has to be converted into an array.

·         $limit (optional): indicates the total number of substrings in which it will split the string.

·         $flags (optional):   used to bring some changes to the array.

the flag represents the condition on which the final array will be returned.

These options or conditions are:

·         PREG_SPLIT_NO_EMPTY: used to remove the empty string and the non-empty strings will be returned.

·         PREG_SPLIT_DELIM_CAPTURE: used to get the delimiter in the resulting array as well. If this flag is used, then the expression within the parenthesis will also be captured as an array element.

·         PREG_SPLIT_OFFSET_CAPTURE: this function return a pair as an array element.

Example :- convert string to array in PHP.

<?php

    // define a string

    $my_string = 'hello';    

    // -1 -> no limit

    $my_array = preg_split('//', $my_string , -1, PREG_SPLIT_NO_EMPTY); 

    // print the array

    echo "The converted array is: <br>";

    print_r($my_array); // h, e, l, l, o

?>


 

4.  str_word_count() Function

Gives information about the string, such as the number of characters in the string, and so on. 

 

Syntax:

str_word_count ( $string , $returnVal, $chars )

Parameters

·         $string: A string that has to be converted into an array.

·         $returnVal (optional): indicates what the function will return.

This is an optional parameter and by default, it is 0.

It can take three different kinds of values:

0: value by default. the function will return the total count of the number of

     words in the input string.

1: set to 1, then the function will return an array containing all the words of the

    string as its elements.

2: If set to 2, then the function will return an array containing the key-value

    pairs. The key will be the index of the word and the value will contain the

    word itself.

·         $chars (optional): tells the string to consider the character that is passed as a parameter to as a word as well. 

 

Example:- convert string to array in PHP.

<?php

    // define a string

    $my_string = 'he2llo world';   

    // the character '2' will not be considered as word 

    $my_array1 = str_word_count($my_string, 1);

    // print the array

    echo "The converted array is: <br>";

    print_r($my_array1); // he, llo, world

    // the character '2' is passed as the third argument 

    $my_array2 = str_word_count($my_string, 1, 2); 

    // print the array

    echo "<br><br>The converted array is: <br>";

    print_r($my_array2); // he2llo, world 

?>



In the above example, the string “he2llo world” contains a character 2’ which is not considered a word by default by the function str_word_count(). So, the following expression converts the string into an array and ‘2’ is omitted.

·          

5.  Manually Loop Through the String

  • Converting a string into an array is by manually looping through the string.
  • For this initialize a variable “i”  as 0, and start a loop from ”i” until “i” becomes less than the length of the string.
  • Inside the loop, store each word of the string in the array and increment the variable “i”.

 Example:- A for loop to convert string to array in PHP.

<?php

    // define a string

    $my_string = 'hello world';    

    // declare an empty array

    $my_array = [];

    // traverse the string

    for ($i = 0; $i < strlen($my_string); $i++) {

      if ($my_string[$i] != " ") { 

        $my_array[] = $my_string[$i]; 

      }        

    } 

    // print the array

    echo "The converted array is: <br>";

    print_r($my_array); // h, e, l, l, o, w, o, r, l, d 

?>


Example:- :

<?php

  // Program to change strings in an array to upper case

  $input = array("Practice", "ON", "sjkpgm", "is best");

  // print array before conversion of string

print"Array before string conversion:\n";

print_r($input);

  // Step 1: flip array key => value

$input = array_flip($input);

  // Step 2: change case of new keys to upper

$input = array_change_key_case($input, CASE_UPPER);

  // Step 3: reverse the flip process to 

// regain strings as value

$input = array_flip($input);

  // print array after conversion of string

print"\nArray after string conversion:\n";

print_r($input);

  ?>

Output:

Array before string conversion:

Array

(

    [0] => Practice

    [1] => ON

    [2] => sjkpgm

    [3] => is best

)

 Array after string conversion:

Array

(

    [0] => PRACTICE

    [1] => ON

    [2] => SJKPGM

    [3] => IS BEST

)

 ======================================================= 

Post a Comment

0 Comments