RUKESH JAYARAMULU
RUKESH JAYARAMULU

Reputation: 13

settype() in PHP for an ARRAY is producing Different output

CODE 1: Reading data from Excel sheet. Containing 12 Different values.

The values are : 48,600,5.3,5,1500,6000,85,30,70,30,70,14 .

$BATTCONFIG=$objPHPExcel->getActiveSheet()->rangetoArray('C9:C20',null,true,true,true);

CODE 2: Trying to convert all VALUES in the array $BATTCONFIG to INTEGER using FOR loop.

$y1 = (array_values($BATTCONFIG));
var_dump(y1);
for( $i=0 ; $i<=11 ; $i++ )
{
    settype($y1[$i], "integer"); 
}
var_dump($y1);

But I am not getting the desiered output , I am getting all the values as 1 .

MY OUTPUT:

Before SETTYPE():

 array (size=12)
 0 => 
   array (size=1)
  'C' => float 48
1 => 
array (size=1)
  'C' => int 600
2 => 
array (size=1)
  'C' => float 0.3
3 => 
array (size=1)
  'C' => int 5
4 => 
array (size=1)
  'C' => float 1500
5 => 
array (size=1)
  'C' => int 6000
6 => 
array (size=1)
  'C' => int 85
7 => 
array (size=1)
  'C' => int 30
8 => 
array (size=1)
  'C' => int 70
 9 => 
array (size=1)
  'C' => int 30
10 => 
  array (size=1)
  'C' => int 70
 11 => 
array (size=1)
  'C' => float 14

AFTER SETTYPE():

array (size=12)
0 => int 1
1 => int 1
2 => int 1
3 => int 1
4 => int 1
5 => int 1
6 => int 1
7 => int 1
8 => int 1
9 => int 1
10 => int 1
11 => int 1

Please help me out . I need these Integer values as output to plot my Graph. Thank you in advance.

Upvotes: 0

Views: 2026

Answers (1)

hek2mgl
hek2mgl

Reputation: 157990

There must be another error when populating $y1 with its values. Imagine this simplified example which works as expected:

$arr = array('1','2','3','4','5');
for ($i = 0; $i < 5; $i++) {
    settype($arr[$i], "integer");
}

var_dump($arr);

What gives you :

array(5) {
  [0] =>
  int(1)
  [1] =>
  int(2)
  [2] =>
  int(3)
  [3] =>
  int(4)
  [4] =>
  int(5)
}

After edit of the question (now having $y1 before conversion) it points out, that you aren't aware of that $y1 is multidimensional array. You'll have to change to code to something like this:

$ints = array(); 
foreach($y1 as $index => $cell) {
    $values = array_values($cell);
    $ints []= intval(round($values[0]));
}

var_dump($ints);

Also note, that you are trying to convert floats to int using the settype() function. I would use round() for that

Upvotes: 2

Related Questions