ersezar
ersezar

Reputation: 57

Add condition based on result of str_replace operation

I need to check if str_replace is working while looping.

I am adding condition with str_replace $count as seen below, but this works for first string only.

It can be a condition before or after str_replace starts. I may be missing something and I'm not very good at looping.

<?php
   
   $text = array( 'text1', 'text2', 'text3', 'text4', 'text5' );
   
   $text = implode( ' ', $text );
   
   $maps = array(
     
     // keys and value
     array_fill_keys( array( 'text1' ), 'replaces1' ),
     
     array_fill_keys( array( 'text2' ), 'replaces2' ),
     
     array_fill_keys( array( 'text3' ), 'replaces3' ),
   
   );
   
   foreach( $maps as $map ) {
       foreach( $map as $key => $value ) {
   
          $text = str_replace( $key, $value, $text, $count );
       
     }
   }
       
   if( $count == 0 ) {
       
       $text = '.Yeni>'.$text;
       
   }

   return $text;

?>

Output;

// Here only the first string is fine, the `if($count == 0)` condition after it means nothing, with or without replace.
replaces1 .Yeni>replaces2 .Yeni>replaces3 .Yeni>text4 .Yeni>text5

Expected output;

replaces1 replaces2 replaces3 .Yeni>text4 .Yeni>text5

UPDATE FOR SOLVED

All I needed was array_column. That way, I checked $map for $text before the loop and transformation started, if not needed the loop and transformation didn't start at all.

<?php
   
   $text = array( 'text1', 'text2', 'text3', 'text4', 'text5' );
   
   $text = implode( ' ', $text );
   
   $maps = array(
     
     // keys and value
     array_fill_keys( array( 'text1' ), 'replaces1' ),
     
     array_fill_keys( array( 'text2' ), 'replaces2' ),
     
     array_fill_keys( array( 'text3' ), 'replaces3' ),
   
   );
   
   if( array_column( $maps, $text )  ) {
   
      foreach( $maps as $map ) {
   
       $text = str_replace( array_keys( $map ), array_values( $map ), $text, $count );
       
      }
   }else {
       
       $text = '.Yeni>'.$text;
       
     }

   return $text;

?>

Now Output;

replaces1 replaces2 replaces3 .Yeni>text4 .Yeni>text5

Upvotes: 0

Views: 49

Answers (1)

bugracetin
bugracetin

Reputation: 167

$count variable always equals to 1 in your current situation because in every foreach loop str_replace() function was altering only one element. So, you cannot say that if count is zero do a some process beacuse if count is zero, it leads to "Fatal error".

Upvotes: 1

Related Questions