0

I am reading data from csv file and combining the array.i have below header in csv

First Name,Last Name,Email,Contact No

And i am giving below data in csv in respect of column

Usertest,name,[email protected],645383638

then using array_combine() to combine the data.in this case its working fine and giving me below result

Array
(
    [First Name] => test
    [Last Name] => name
    [Email] => [email protected]
    [Contact No] => 74647454
)

But if i am leaving contact number blank in csv then array_combine() is not working giving me empty array()

Array
(
 
)

$dataKeys   =   First Name,Last Name,Email,Contact No;
$dataValues = 	Usertest,name,[email protected]
$dataArr = array_combine(str_getcsv($dataKeys), str_getcsv($dataValues));

Because the number of parameter is not same in csv header and data field in row.so am not getting how to fix this.

4
  • 1
    Warning: array_combine(): Both parameters should have an equal number of elements Commented Feb 22, 2019 at 6:29
  • The behaviour of array_combine() when the number of provided keys does not match the number of values is documented: " Throws E_WARNING if the number of elements in keys and values does not match." Commented Feb 22, 2019 at 6:30
  • You can use array_pad() to fill the values array with '' (or null) to the required length. Commented Feb 22, 2019 at 6:31
  • Yes i am geeting this error..Warning: array_combine(): Both parameters should have an equal number of elements..but contact number may be blank in csv,in this case how to handle this? Commented Feb 22, 2019 at 6:32

1 Answer 1

7

Whenever you are putting data to csv using array_combine, you can make sure length of both arrays must be the same by the following code.

You can do something like this,

$arr1 = array("First Name", "Last Name", "Email","Contact No");
$arr2 = ["Usertest","name","[email protected]"];
$temp = array_pad($arr2, count($arr1),'');
$res = array_combine($arr1,$temp);
print_r($res);

Output

Array
(
    [First Name] => Usertest
    [Last Name] => name
    [Email] => [email protected]
    [Contact No] => 
)

Demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.