Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 08/11/2025 in all areas

  1. the anonymous function has local variable scope, like any php function. you can add use ($total) to the definition to make the variable available inside the function - $resultsCalcArray = array_map(function($votes) use ($total) { as to the posted code - the input call-time parameter should only be the $id and you should only call this function after you have validated the $id. this function should also have an existing pdo connection as an input call-time parameter. it is the wrong responsibility for this function to make a database connection. there's no point is defining and initializing $conn, $stmt, and $rs. don't use the global keyword to get data into or out of a function. this is not general purpose and results in spaghetti code that is hard to debug problems in. all input data to a function should be supplied as call-time parameters and the function should return the result it produces to the calling code. if you set the default fetch mode to assoc when you make the database connection, you won't need to specify it in each fetch statement. fetchAll() won't ever return a null, so the !is_null() test will never fail and should be removed. since you are only operating on the 'kount' column, that is the only thing the query should SELECT. if you have some reason to select other columns, you can build (or add to) the $resultsCalcArray from just the 'kount' column by using array_column(). you can directly get the total of the $resultsCalcArray 'kount' values by using array_sum(). no in-line code after the throw $e; statement will ever get executed and should be removed. there's generally no point in freeing up result sets, closing prepared query handles, or closing database connections in your code, at all, and there's certainly no point in doing this inside a function, since all those things get destroyed when the function call ends.
    1 point
  2. To include a variable that is defined externally to the map function you need "use()" $calcArray = [ 34, 56, 82 ]; $total = 10; $calcArray = array_map ( function($v) use ($total) { return round($v / $total); }, $calcArray ); echo '<pre>' . print_r($calcArray, 1) . '</pre>'; Alternatively, you can use this syntax... $calcArray = [ 34, 56, 82 ]; $total = 10; $calcArray = array_map ( fn($v) => round($v / $total), $calcArray ); echo '<pre>' . print_r($calcArray, 1) . '</pre>'; See https://www.php.net/manual/en/functions.arrow.php
    1 point
This leaderboard is set to New York/GMT-04:00
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.