John Davidson

php - Improve code lisibility on field validation

0 comments
Message:


I receive an ad and I have to format the French phone number, which must not exceed 10 characters and contain only numbers. In case the criteria are not met I would like to return null.


I am not satisfied with my solution, would you have a simpler solution?


<?php

function formatAds(array $ad): array
{
$ad['last_name'] = ucfirst($ad['last_name']);
$ad['first_name'] = ucfirst($ad['first_name']);

$phoneNumber = str_replace(' ', '', $ad['phone_number']);
$ad['phone_number'] = is_numeric($phoneNumber) && strlen($phoneNumber) === 10 ? $phoneNumber : null;

return $ad;

}


$ad = [
"last_name" => "foo",
"first_name" => "bar",
"phone_number" => "04 55 66 77 11",
];


print_r(formatAds($ad));

You can see the code here: https://3v4l.org/PdTRG



My Answer:
Here is a simpler solution for the field validation in your code:

php
function formatAds(array $ad): array
{
$ad['last_name'] = ucfirst($ad['last_name']);
$ad['first_name'] = ucfirst($ad['first_name']);

$phoneNumber = preg_replace('/\D/', '', $ad['phone_number']); // Remove all non-numeric characters
$ad['phone_number'] = (strlen($phoneNumber) === 10) ? $phoneNumber : null;

return $ad;
}

$ad = [
"last_name" => "foo",
"first_name" => "bar",
"phone_number" => "04 55 66 77 11",
];

print_r(formatAds($ad));


This solution uses a regular expression to remove all non-numeric characters from the phone number before checking its length. This makes the code more concise and easier to read.

Rate this post

3 of 5 based on 6484 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us