I just want to use array_walk() with ceil() to round all the elements within an array. But it doesn't work.
The code:
$numbs = array(3, 5.5, -10.5);
array_walk($numbs, "ceil");
print_r($numbs);
output should be: 3,6,-10
The error message:
Warning: ceil() expects exactly 1 parameter, 2 given on line 2
output is: 3,5.5,-10.5 (Same as before using ceil())
I also tried with round().
Use array_map instead.
$numbs = array(3, 5.5, -10.5);
$numbs = array_map("ceil", $numbs);
print_r($numbs);
array_walk actually passes 2 parameters to the callback, and some built-in functions don't like being called with too many parameters (there's a note about this on the docs page for array_walk). This is just a Warning though, it's not an error.
array_walk also requires that the first parameter of the callback be a reference if you want it to modify the array. So, ceil() was still being called for each element, but since it didn't take the value as a reference, it didn't update the array.
array_map is better for this situation.
I had the same problem with another PHP function.
You can create "your own ceil function".
In that case it is very easy to solve:
function myCeil(&$list){
$list = ceil($list);
}
$numbs = [3, 5.5, -10.5];
array_walk($numbs, "myCeil");
// $numbs output
Array
(
[0] => 3
[1] => 6
[2] => -10
)
The reason it doesn't work is because ceil($param) expects only one parameter instead of two.
What you can do:
$numbs = array(3, 5.5, -10.5);
array_walk($numbs, function($item) {
echo ceil($item);
});
If you want to save these values then go ahead and use array_map which returns an array.
UPDATE
I suggest to read this answer on stackoverflow which explains very well the differences between array_map, array_walk, and array_filter
Hope this helps.
That is because array_walk needs function which first parameter is a reference &
function myCeil(&$value){
$value = ceil($value);
}
$numbs = array(3, 5.5, -10.5);
array_walk($numbs, "myCeil");
print_r($numbs);
Related
I'm trying to sort numbers on given command line argument as sortnumb$ php phpsort.php 2 5 3 8and it should print as 2 3 5 8. I have tried following code but I don't know how to save given arguments in an array to use "sort" command in PHP. please advice
$argv[1]
$numbers = array($argv[1]);
sort($numbers);
$arrlength=count($numbers);
for($x=0;$x<$arrlength;$x++)
{
echo $numbers[$x];
echo "\n";
}
$argv contains the array of numbers that you are passing, but $argv[0] contains the script name. You can read about here in the PHP manual.
So you can take out the array items you are interested in, using array_slice:
$numbers = array_slice($argv, 1);
The second parameter says to slice from the second item of the index.
Then the rest of the code is correct as you had it.
Although you can use a foreach loop instead (read about it here):
sort($numbers);
foreach ($numbers as $number) {
echo $number."\n";
}
the argument already saved at $numbers array
you can use $numbers variable to do whatever you want
You can make array using the ' ' (space delimiter) and then use any of the sorting function on that array
I'm trying to use create_function in order to find out how many times a certain value occurs in a particular array.
while (!empty($rollcounts)){
// Take the first element of $rollcounts
$freq = count(array_filter($rollcounts,create_function("$a","return $a == $rollcounts[0]")));// Count how many times the first element of $rollcounts occurs in the list.
$freqs[$rollcounts[0]] = $freq; // Add the count to the $frequencies list with associated number of rolls
for($i=0;$i<count($rollcounts);$i++){ // Remove all the instances of that element in $rollcounts
if(rollcounts[$i] == $rollcounts[0]){
unset($rollcounts[$i]);
}
}
} // redo until $rollcounts is empty
I get a "Notice" message complaining about the $a in create_function(). I'm surprised, because I thought $a was simply a parameter. Is create_function() not supported in my version of php? phpversion() returns 5.6.30 and I'm using XAMPP. The error message:
Notice: Undefined variable: a in /Applications/XAMPP/xamppfiles/htdocs/learningphp/myfirstfile.php on line 34
So, if I'm reading your question correctly, I think you want to count the occurrences of each element in the array? If so just use array_count_values e.g. [1, 1, 2, 2, 3] -> [1 => 2, 2 => 2, 3 => 1]
$freqs = array_count_values($rollcounts);
This way you can skip your while loop.
You should use something like ...
$freq = count(array_filter($rollcounts,function($a) {return $a == $rollcounts[0];}));
Have a read of http://php.net/manual/en/functions.anonymous.php which explains a bit more about them.
Very simple but I was wondering why this is not working.
I'm trying shuffle an array and output the results (in a single line structure)
this is my code :
echo shuffle(array("A","B","C"))[0];
Small tweak needed here ;)
Your basic logic is a little bit wrong. You're interested in only one value, I assume? To solve it with that logic in mind, you can do it like this:
echo array_rand(array_flip(['A', 'B', 'C']));
Try below code
$arr = array("A","B","C");
shuffle($arr);
echo $arr[0];
I know that this is not the best solution for you, but it works!
print_r( ( $b=array('A', 'B', 'C') ) && shuffle($b) ? next($b) : null );
How this works:
Assign the array to the variable $b
Shuffle the variable $b
If the shuffle() succeeded:
return the next element in the array
If the shuffle() failed:
return null
Some might think: "Why didn't he used the current() function?"
Well, it seems that the function shuffle simply changes the order of the keys, but the pointer is always pointing to the same element. This means that current() will always return 'A'.
Apparently, this behaviour changed on PHP 5.4 to set the pointer to the first element.
TRY THIS SIMPLE FUNCTION
$my_array = array("A","B","C","D","E");
shuffle($my_array);
print_r($my_array);
You will need to pass the array in a seperate variable. Also, shuffle() itself just returns a boolean value, so you need to return an array element instead of the output of the function.
$ar = array("A","B","C");
shuffle($ar);
echo $ar[0];
When using php array_fill and negative indices, why does php only fill the first negative indice and then jump to 0.
For example:
array_fill(-4,4,10) should fill -4, -3, -2, -1 and 0 but it does -4, 0, 1, 2, 3
The manual does state this behaviour but not why.
Can anyone say why this is?
Looking at the source for PHP, I can see exactly why they did this!
What they do is create the first entry in the array. In PHP, it looks like:
$a = array(-4 => 10);
Then, they add each new entry like this:
$count--;
while ($count--) {
$a[] = 10;
}
If you do this exact same thing yourself, you'll see the exact same behavior. A super short PHP script demonstrates this:
<?php
$a = array(-4 => "Apple");
$a[] = "Banana";
print_r($a);
?>
The result: Array ( [-4] => Apple [0] => Banana )
NOTE
Yes, I did put in PHP instead of the C source they used, since a PHP programmer can understand that a lot better than the raw source. It's approximately the same effect, however, since they ARE using the PHP functions to generate the results...
Maybe because it's stated in the doc: http://www.php.net/manual/en/function.array-fill.php
If start_index is negative, the first index of the returned array will be start_index and the following indices will start from zero (see example).
Is there any simple way of checking if all elements of an array are instances of a specific type without looping all elements? Or at least an easy way to get all elements of type X from an array.
$s = array("abd","10","10.1");
$s = array_map( gettype , $s);
$t = array_unique($s) ;
if ( count($t) == 1 && $t[0]=="string" ){
print "ok\n";
}
You cannot achieve this without checking all the array elements, but you can use built-in array functions to help you.
You can use array_filter to return an array. You need to supply your own callback function as the second argument to check for a specific type. This will check if the numbers of the array are even.
function even($var){
return(!($var & 1));
}
// assuming $yourArr is an array containing integers.
$newArray = array_filter($yourArr, "even");
// will return an array with only even integers.
As per VolkerK's comment, as of PHP 5.3+ you can also pass in an anonymous function as your second argument. This is the equivalent as to the example above.
$newArray = array_filter($yourArr, function($x) { return 0===$x%2; } );
Is there any simple way of checking if all elements of an array [something something something] without looping all elements?
No. You can't check all the elements of an array without checking all the elements of the array.
Though you can use array_walk to save yourself writing the boilerplate yourself.
You can also combine array_walk with create_function and use an anonymous function to filter the array. Something alon the lines of:
$filtered_array = array_filter($array, create_function('$e', 'return is_int($e)'))