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.
Related
Example:
$array = ['name', 'address'];
It contains $array[0] and $array[1] only.
If i try $array[2] i should receive an error.
So, i want to avoid these errors by checking it in a if statement. How can i check if an array contains a value in certain index?
You can use the isset function:
if(isset($array[2])) {
The second way to make it work is check how big is an array:
if(count($array) >= 3) { ... } // three or more elements: 0, 1, 2...
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);
Quick PHP problem here :
When doing a for each statement I have to echo it in a perticular syntax I.E
|First_Name:bob,jim,alex,gary|Last_Name:Smith,Doe,foo|Age:11,12,13
I have so far manage to achieve this syntax except for the last value of each of the for loop as I get this result
|First_Name:bob,jim,alex,gary,|Last_Name:Smith,Doe,foo,|Age:11,12,13,
so the is an extra comma in every itteration of the second loop.
Is there a way to get rid of the comma for the last value only.
Try this:
$abc = "First_Name:bob,jim,alex,gary,";
$rest = substr($abc, -1);
There is a built-in function for joining array elements, called implode, which I suggest you should use:
$a = [1, 2, 3];
$s = implode(",", $a);
// result: "1,2,3"
NB: The short array notation was introduced in PHP 5.4. For older versions, use this line instead to initialize an array:
$a = array(1, 2, 3);
I am facing a problem that undefined offset :1 in line 3. I can't understand that what type of error it is.
Can anyone tell me that why such error occurs in php
Undefined offset in line : 3
foreach ($lines as $line)
{
list($var,$value) = explode('=', $line); //line 3
$data[$var] = $value;
}
Your are getting PHP notice because you are trying to access an array index which is not set.
list($var,$value) = explode('=', $line);
The above line explodes the string $line with = and assign 0th value in $var and 1st value in $value. The issue arises when $line contains some string without =.
I know this an old question and the answer provided is sufficient.
Your are getting PHP notice because you are trying to access an array
index which is not set.
But I believe the best way to overcome the problem with undefined indexes when there are cases where you may have an empty array using the list()/explode() combo is to set default values using array_pad().
The reason being is when you use list() you know the number of variables you want from the array.
For example:
$delim = '=';
$aArray = array()
$intNumberOfListItems = 2;
list($value1, $value2) = array_pad(explode($delim, $aArray, $intNumberOfListItems ), $intNumberOfListItems , null);
Essentially you pass a third parameter to explode stating how many values you need for your list() variables (in the above example two). Then you use array_pad() to give a default value (in the above example null) when the array does not contain a value for the list variable.
This is caused because your $line doesn't contain "=" anywhere in the string so it contains only one element in array.list() is used to assign a list of variables in one operation. Your list contains 2 elements but as from data returned by implode, there is only one data. So it throws a notice.
A way to overcome that is to use array_pad() method.
list($var,$value) = array_pad(explode('=', $line),2,null);
by doing list($var, $value) php will expect an array of 2 elements, if the explode function doesn't find an equal symbol it will only return an array with 1 element causing the undefined offset error, offset 1 is the second element of an array so most likely one of your $line variables doesn't have an equal sign
This is due to the array. The array index is not showing due to this undefine offset error will come...
So please check the array with print_r function.
The list language construct is used to create individual variables from an array. If your array doesn't have enough elements for the number of variables you are expecting in the list call, you will get an error. In your case you have 2 variables so you need an array with 2 items - indexes 0 and 1.
http://php.net/manual/en/function.list.php
Solution:
$lines = array('one' => 'fruit=apple', 'two' => 'color=red', 'three' => 'language');
foreach ($lines as $line)
{
list($var,$value) = (strstr($line, '=') ? explode('=', $line) : array($line, ''));
$data[$var] = $value;
}
print_r($data);
Try this one..
For reference
http://in1.php.net/manual/en/function.list.php
http://in1.php.net/manual/en/function.explode.php
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).