Skip to content
Advertisement

Php apply function in array if next entry is integer (Concatenate a valid FEN string)

Trying to build a valid FEN string.

Given this 8*8 array example, symbolizing a checker board, (“1” are empty squares):

$checkerboard = [["r","n","b","q","k","b","n","r"],["p","p","p","p","p","p","p","p"],["1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1"],["1","1","1","1","P","1","1","1"],["1","1","1","1","1","1","1","1"],["P","P","P","P","1","P","P","P"],["R","N","B","Q","K","B","N","R"]]

In situ, this is the position:

enter image description here

The valid result I am looking for is:

rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR

And by now my output is:

rnbqkbnr/pppppppp/11111111/11111111/1111P111/11111111/PPPP1PPP/RNBQKBNR

Obviously, any integer entry in the array should be sum to the next, only if the next entry is an integer, and if so the next entry should be discarded till the end.

By iterating the array, I am not sure how to apply something like array_walk() or array_map() here in a simple way. Maybe a simple string operation is enough?

  $FEN = "";
  for ($i = 0;$i < 8;$i++){
    for ($j = 0;$j < 8;$j++){
      if ($checkerboard[$i][$j] === "1"){
        if ($checkerboard[$i][$j + 1] === "1"){
           /* How to iterate till the end */
           $FEN .= (int)$checkerboard[$i][$j] + (int)$checkerboard[$i][$j+1];
        }
      } else {
        $FEN .= $checkerboard[$i][$j];
      }      
    }
    $FEN .= "/";
  }

Any insights?

Example online: https://3v4l.org/tuqqo

Advertisement

Answer

$checkerboard = [["r","n","b","q","k","b","n","r"],["p","p","p","p","p","p","p","p"],["1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1"],["1","1","1","1","P","1","1","1"],["1","1","1","1","1","1","1","1"],["P","P","P","P","1","P","P","P"],["R","N","B","Q","K","B","N","R"]];

$parts =  array();
foreach ($checkerboard as $innerArray) {
    $num = null;
    $str = '';
    foreach($innerArray as $innerval){
        if(is_numeric($innerval)){
            $num += (int) $innerval;
        }
        else{
            if(!is_null($num)){
                $str .=$num;
                $num = null;
            }
            $str .=$innerval;
        }
    }
    if(!is_null($num)){
        $str .=$num;
    }
    array_push($parts,$str);
}
$result = implode('/',$parts);

above code will generate required output and store it on the $result.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement