How to print on screen or console, an array of strings in php

0

I've been seeing the documentation but it's not clear how I do it. I have an array of strings:

$remetente = $con->real_escape_string($_REQUEST['rem']);
$arrai= array();
$remetenteArray[] = str_split($remetente, 1);

As you can see, $remetenteArray[] is an array of strings, these strings have only one character each. What I need is to iterate over this array and print on the screen only the numbers that are in it, and save them to a string.

I'll create a regular expression to get the numbers, but the problem at the moment is how to print those strings that make up the array ...

    
asked by anonymous 27.05.2018 / 14:53

1 answer

1

What you want is to individually check each array element. That is, it would look something like this:

for ($i=(int)0; $i<count($remetenteArray); $i++){
    print ">".$remetenteArray[$i]."< ";
}

I think you should have tried something like this and received something like:

PHP Notice:  Array to string conversion in ..

It turns out that you made a mistake in setting array :

$remetenteArray[] = str_split($remetente, 1);

When you place the open and close square brackets, you have created an array inside the other one, that is, the first item in it contains the array resulting from the str_split() function. remove them as the loop will work correctly.

But since you only want to return the string's string numbers within the array , there is neither the need to juggle this whole thing, to string and spit soon the array .

function onlyNumbers($str){
        $result=[];
        for($i=0; $i<strlen($str); $i++){
                $j = substr($str, $i,1);
                if ($j>="0" and $j<="9") $result[]=$j;
        }
        return $result;
}

So:

$remetente = "0 A 1 B 2 C 3 D 4";
print_r(onlyNumber($remetente));

Will result in:

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
)

Incidentally, it was thanks to print_r() that I discovered your error. : -)

    
27.05.2018 / 15:37