w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Adding dollar sign before each string in array?

For each value, check if the first char (or the whole value) is made of characters with ctype_alpha, then prepend with $ :

// $arr is your array as defined in your question
foreach ($arr as &$val) {
 //OR if (ctype_alpha($val[0])) { 
 if (ctype_alpha($val)) {
   $val = '$' . $val;
 }
}

var_dump($arr);

Output :

array(6) {
  [0]=>
  string(3) "$he"
  [1]=>
  string(1) "+"
  [2]=>
  string(3) "$is"
  [3]=>
  string(1) "+"
  [4]=>
  string(7) "$genius"
  ...
}

Second solution, checking if it has a char at any position :

foreach ($arr as &$val) {
  $tmp = str_split($val); 
  foreach ($tmp as $char) {
    if (ctype_alpha($char)) {
      $val = '$' . $val;
      break;
    }
  } 
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.