Create the same function in php

1

I have the following function in javaScript :

function teste(ctrl) {
  var str = ctrl.value;
  var str = str.split(" ");

  if (str.every(isBigEnough) && str.length >= 2) {
    alert(true);
  } else {
    alert(false);
  }
}

function isBigEnough(element, index, array) {
    return element.length > 1;
}
<input id="nome" name="nome" type="text" placeholder="Nome completo" required onchange="teste(this)">

I want to replicate it in php to have this validation also in back-end There is a function in php similar, array_walk only I am not getting it yet. It would be something like:

function isBigEnough($item, $key) {
    return strlen($item) >= 2;
}

function validaNome($value) {
    var $str = $value;
    var $str = explode(" ",$value);

    if (array_walk($str, 'isBigEnough') && count($str) >= 2) {
        return true;
    }else{
        return false;
    }
}
    
asked by anonymous 07.10.2016 / 20:57

1 answer

1

Use array_map to apply a function to each element of the array, so you will check the number of characters in each element.

<?php 

    function isBigEnough($item){

        if(strlen($item) > 2){

            return true;

        } else {

            return false;

        }

    }


    function validaNome($nome){

        $arrayNome = explode(" ", $nome);

        if(in_array(false, array_map("isBigEnough", $arrayNome))){

            echo "Não é válido!";

        } else {

            echo "ok!";

        }

    }

    validaNome("Marcelo Bonifazio");


?>

Other programmers also like to avoid using explicit loops. Why, I do not know, because loops are usually 2x faster and less complicated to use than these types of codes. If you can comment later, just out of curiosity, I thank you. =)

But there it is. Hugs!

    
08.10.2016 / 03:40