How to Replace Array Strings in PHP

104 52
    • 1). Open your PHP file in a text editor, such as Windows Notepad.

    • 2). Enter an array and assign it string values as below:

      $my_array = array('str 1', 'str 2', 'str 3', 'str 4', 'str 2');

    • 3). Create two variables as below, assigning them the search and replace string values for your array:

      $search_value = "str 2"; $replace_value = "str 7";

    • 4). Sort through the array with a "foreach" loop as below, using the "strcmp" function to check each array value for a match with the search string and replace it with the replacement string:

      foreach($my_array as $k => $value) { if (strcmp($value,$search_value)==0) { $my_array[$k] = $replace_value; } }

      This will replace the two instances of "str 2" with "str 7" and modify the array.

    • 5). Save the PHP file.

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.