How to put data into an array

$data = array('green'=>4.02, 'red'=>1.85, 'yellow'=>12.05);

function me($x,$y){echo $x*$y;}

$datum = '50';
$newData = array();

foreach($data as $row)
{
    $val = me($row, $datum);
    
    echo $val.'<br>';
    //  ************* trying to put the function output into  an aaray, but it is not working*************
    $newData[] = $val;
}

foreach($newData as $row)
{
    echo ''.$row; // ************** does not work
}

EDIT
This post has been reformatted by enclosing the code block in 3 backticks
```
on their own lines.

What is the “me” function returning?

// the product
function me($x, $y)
{
return $x * $y;
}

My main objective is to get an array apply a function to it and then get back the array to sum the individial array components (green, red, yellow as seen here)

Yes that is the issue. You don’t want to echo the result but return the result.

function me($x,$y){
    $new_value = $x * $y;
    return $new_value;
}
1 Like

I get it! Thanks

If you need that data key be sure to add it when building newData.

<?php
$data = array('green'=>4.02, 'red'=>1.85, 'yellow'=>12.05);

function me($x,$y){
    $new_value = $x * $y;
    return $new_value;
}

$datum = '50';
$newData = array();

foreach($data as $key => $row)
{
    $val = me($row, $datum);
    
    //  ************* trying to put the function output into  an aaray, but it is not working*************
    $newData[$key] = $val;
}
echo "<pre>";
print_r($newData);
echo "</pre>";
/*
foreach($newData as $row)
{
    echo '<br />'.$row; // ************** does not work
}
*/
?>
1 Like

This is a use case for array_walk

<?php
$data = array('green'=>4.02, 'red'=>1.85, 'yellow'=>12.05);
$datum = '50';
 
array_walk($data, function(&$val, $key, $datum) {
  $val *= $datum;
}, $datum);

echo "<pre>";
print_r($data);
echo "</pre>";

K, there’s a few things going on here that are advanced so I’ll point them out. First, I’m using a closure, which is a function declared on the fly (since PHP 5.3) which is passed as the second argument to array_walk. Array walk traverses the array and gives the closure at least two arguments - The value, the key, and then the third argument on are arguments that were passed to array walk after the closure (see its docs, and yes it can be overloaded though the docs don’t make this clear).

Second, the closure receives the value of each array element by reference (that’s what the & does). This means any operation performed on that variable is to happen to the original variable, or in this case original array element. As a result of this behavior we don’t need to return anything.

Finally, the *= operation is a shorthand for $val = $val * $datum;

2 Likes
<?php

/*
I have another short-coming:
- The user makes choices which is put in an array $datum
- The database is put in an array $database 
- I will like to multiply EACH user's data($datum) with every database value($database), but the function won't work
*/
function mul($x,$y){

    foreach($x as $data)// $datum, user's data
    {
        foreach($y as $db)// db data
        {
        return $data * $db;
        }
    }
}


$database = array('green'=>4.02, 'red'=>1.85, 'yellow'=>12.05);// database value

$datum = array(2,6,8,4);// user's data, it is variable: it may be 1 to any number of digits 

$newData = array();
foreach($datum as $row)
{
    $val = mul($datum, $row); // the function seems not to be correct
    
    $newData[] = $val;
}
?>

EDIT
This post has been reformatted by enclosing the code block in 3 backticks
```
on their own lines.

Your function doesn’t work because you if you issue a return in the middle of any iteration that iteration will be halted.

Also, you need to brush up on your math skills. If you need to multiply each user’s input by every database value you should first find the product of the database values.

$product = 1; // Not 0, multiplication by 0 is always 0.
foreach ($database as $d) { $product *= $d; }

Then you take that product and iterate it over the user inputs in a manner not unlike the code you’ve already seen. You don’t need to repeat the iteration over the database values, it’s never going to change - this is basic math.

EDIT: One other thing - you may be in for a nasty surprise depending on your CPU’s mood. Floating point operations can be… fussy. If the database values are currency it’s safer to use the bcmath library.

http://php.net/manual/en/ref.bc.php

See also

Some good points Michael.

nkarimbicho, Keep the fuction outside the loops.

<?php
$data = array('green'=>4.02, 'red'=>1.85, 'yellow'=>12.05);
$datum = array(2,6,8,4);

function me($x,$y){
    $new_value = $x * $y;
    return $new_value;
}

$newData = array();
$newDataWithKey = array();
foreach($datum as $dat):
    foreach($data as $key => $row):
        $val = me($row, $dat);       
        $newData[] = $val;
        $newDataWithKey[$key][] = $val;
    endforeach;
endforeach;


echo "<pre>";
print_r($newData);
print_r($newDataWithKey);
echo "</pre>";
?>

And wrapping Michael’s code in foreach will total each datum number times data value.

foreach($datum as $dat):
array_walk($data, function(&$val, $key, $dat) {
  $val *= $dat;
}, $dat);
endforeach;

echo "<pre>";
print_r($data);
echo "</pre>";

Results of all three arrays

Array
(
    [0] => 8.04
    [1] => 3.7
    [2] => 24.1
    [3] => 24.12
    [4] => 11.1
    [5] => 72.3
    [6] => 32.16
    [7] => 14.8
    [8] => 96.4
    [9] => 16.08
    [10] => 7.4
    [11] => 48.2
)
Array
(
    [green] => Array
        (
            [0] => 8.04
            [1] => 24.12
            [2] => 32.16
            [3] => 16.08
        )

    [red] => Array
        (
            [0] => 3.7
            [1] => 11.1
            [2] => 14.8
            [3] => 7.4
        )

    [yellow] => Array
        (
            [0] => 24.1
            [1] => 72.3
            [2] => 96.4
            [3] => 48.2
        )

)
Array
(
    [green] => 1543.68
    [red] => 710.4
    [yellow] => 4627.2
)

I appreciate the highlights Micheal, but the logic can only allow the user’s data, $userData = array(8,2,5.6); to be multiplied through every chosen database entry (array indices green, red and yellow).
Drummin, thank you is the least I can say, while implementing all of these I realised my database output is a multidimensional array, and I have had it hot since afternoon trying to do something, but in vain, can someone please help me out. . My database outputs a multidimensional array like
Array
(
[0] => Array
(
[green] => 2.540
[red] => 202.340
[yellow] => 56.582
)

[1] => Array
    (
        [green] => 155.000
        [red] => 465.320
        [yellow] => 0.002
    )

[2] => Array
    (
        [green] => 54.856
        [red] => 0.000
        [yellow] => 89.122
    )

)
$userData = array(8,2,56);

foreach($userData as $userDatum):
foreach($dbData as $key => $dbDatum):

    $val = me($dbDatum, $userDatum); // the function can not run this. Saying Fatal error: Unsupported operand types in C:\wamp\www\tutos\includes\functions.inc.php on line 4
    $newData[$key][] = $val;
endforeach;

endforeach;

//to be at the top
function me($x,$y){
$new_value = ($x * $y); //line 4
return $new_value;
}

I took off time to go through the array documentation and I learnt the different functions possible and found array_walk_recursive() as a good fit for what I want to do. But I still have some short-coming. Please can someone give this piece of code a try?

$newValue = array();

function myfxn(&$value,$key, $data)
{
$value = $value * $data;
/*
*************** The problem *********************
######## This function simply does ($a1[‘green’]: 58 * 10 * 5.5) #############

I want each $data to multiply $value once and the product fed in an array, and be summed before being output as $newValue
so I use this:
###############################################
$value = $value * $data;

$newData[] = $value;

$newValue = array_sum($newData);

###############################################
But print_r($newValue); outputs an empty array.
*/
}

$a1=array(“green”=>58,“red”=>25, “yellow”=>24);
$a3=array(“green”=>0.58,“red”=>0.25, “yellow”=>16);

$userData = array(10, 5.5);

$a2=array($a1,$a3);

foreach(userData as $data):
array_walk_recursive($a2,“myfxn”, $data);
endforeach;

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.