Create the same function in php

Asked

Viewed 79 times

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 the back-end There is a similar php function, the array_walk I’m just not quite there 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;
    }
}
  • needs to be similar to javascript version technique?

  • needs to perform the same action, in javascript I blow up the string and I check the size of each element of it, if each element is larger than 2 ok, otherwise it does not pass, I wanted to avoid the foreach, but if it’s the least painful way, okay

  • Okay, what matters is the end result.

1 answer

1


Use the 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 don’t 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 appreciate. =)

But it’s there. Hug!

  • The idea is not to escape from the loop, it is to apply the same logical function of verification in each element, I am only replicating the same functions that I created in front-end in back-end, no matter what method used, loop, recursiveness, passed parameter and so on :)

  • I’ll test her :D

  • I get it. I’ve made changes... Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.