-1

I use these code to splite a Phone number String into area code and call number.

When i use "strlen($areacode)" i get a php warning strlen() expects parameter 1 to be string, array given.

When is use count () instead of strlen(), the script is wrong execute. I get the result "No AreaCode found".

What make i wrong?

<?php
$phonenumber = '0349152023';
$link = mysqli_connect('host', 'DB', 'Pass','User') or die(mysqli_error());
$db_selected = mysqli_select_db( $link, 'DB');
$ErsteDrei = substr($phonenumber,0,3); 
$array = array();
$query = mysqli_query($link, "SELECT Areacode FROM `Areacodes` WHERE Vorwahl like '".$ErsteDrei."%' ORDER BY CHAR_LENGTH(Vorwahl) DESC");
while($row = mysqli_fetch_assoc($query)){
  $array[] = $row;
}
foreach ($array as $areacode) {
    $subString = substr($phonenumber, 0, strlen($areacode));
    if ($subString == $areacode) {
        $phone = $subString." ".substr($phonenumber, strlen($areacode));
    }
}
if (!empty($phone)) {
    echo $phone;
}

else {
    echo "No AreaCode found.";
}
?>
soo29
  • 17
  • 8
  • if (empty($phone)) { echo "No AreaCode found."; } I am not sure but try Like this. – Siva Ganesh Oct 10 '17 at 13:01
  • 1
    `$row` is an array with 1 index, `$row['Areacode']`. So either assign it like that or access the index in the loop as needed `$areacode['Areacode']`. – chris85 Oct 10 '17 at 13:03
  • 1
    do var_dump($array) to get visibility on the structure and how to call elements within the array you are accessing; may help. – lovelace Oct 10 '17 at 13:12
  • Read about [`strlen()`](http://php.net/manual/en/function.strlen.php) and [`count()`](http://php.net/manual/en/function.count.php). They are different functions that have different purposes. – axiac Oct 11 '17 at 08:20

1 Answers1

2

What is happening here is that you are fetching the data as associative array "mysqli_fetch_assoc". So each $row will actually be an array like this:

array("Areacode"=>"0349"); //or whatever the code is

You can do the following:

foreach ($array as $areacode) {
    $subString = substr($phonenumber, 0, strlen($areacode["areacode"]));
    if ($subString == $areacode) {
        $phone = $subString." ".substr($phonenumber, strlen($areacode));
    }
}

Or use "mysqli_fetch_array" instead of "mysqli_fetch_assoc"

Lamar
  • 1,761
  • 4
  • 24
  • 50