0

I have the array variable $geo_detail=Array ( [0] => nsu [1] => us east [2] => us west ) I want to replace nsu with NSU ,us east to US East and us west to US West

I have tried as

if (count($geo_detail))
          {
              foreach($geo_detail as $geos=>$key){
                  if (str_word_count($key) =='1')
                     $key= strtoupper($key);
                  elseif((str_word_count($key) =='2'))
                   $key= ucwords($key); 
              }
          }
         return $geo_detail;

but return Array ( [0] => nsu [1] => us east [2] => us west )

how to replace the array value

3 Answers 3

1

You need to change the real Key/Value from your array, replace

$key= strtoupper($key);

to

geo_detail[$geos] = strtoupper($key);

and

$key= ucwords($key); 

to

geo_detail[$geos] = ucwords($key);
Sign up to request clarification or add additional context in comments.

2 Comments

The result with the changes is array (3) {[0] => string (3) "NSU" [1] => string (7) "Us East" [2] => string (7) "Us West"} and not US East and US West as required in the task !
this is to update his array, not to do his work about capitalize
0
$geo =  ['nsu', 'us west', 'us east'];

foreach ($geo as $k => $g) {
    
    // explode string
    $words = explode(" ", $g);
    
    $string = "";
    foreach($words as $w) {
        
        // 3 chars and below, all caps
        if (strlen($w) <= 3) {
            $w = strtoupper($w);
        } else {
            
            $w = ucwords($w);
        }
        
        $string = $string . $w . " ";
    }
    
    
    // assign new value, remove space at end
    $geo[$k] = substr($string, 0, -1);
}

print_r($geo);

Result

Array ( [0] => NSU [1] => US West [2] => US East )

Comments

0

The words must be treated separately. I understand the task as follows:

With the first word everything should be capitalized, with the second word only the first letter.

I also used explode() for splitting.

$geo_detail = ['nsu','us east','us west'];

$result = [];
foreach($geo_detail as $key => $item){
  $wordArr = explode(' ',$item);
  $new = strtoupper($wordArr[0]);
  if(isset($wordArr[1])){
    $new .= " ".ucwords($wordArr[1]);
  }
  $result[$key] = $new;
}

$expected = ['NSU','US East','US West'];
var_dump($result === $expected);//bool(true)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.