How do I make an array without using array_count_values()? - php

I have an array, $arrayName = array(1,2,1,3,4,3,2,5);. I want the result as:
Array (
[1] => 2
[2] => 2
[3] => 2
[4] => 1
[5] => 1
)
Without using array_count_values(), what is the logic behind array_count_values()?

This method will only loop each value once compared to other methods posted here.
Instead of looping the full array I get unique values and count them with array_keys and count.
$arrayName = array(1,2,1,3,4,3,2,5);
$values = array_unique($arrayName);
Foreach($values as $val){
$count[$val] = count(array_keys($arrayName, $val));
}
Var_dump($count);
https://3v4l.org/EGGJq
In your example I think my method may actually be slower than looping the full array, but if this was a large array there may be a benefit of not looping the full array.

The best solution is to use array_count_values function. That counts frequency of values in an array.
See this - http://php.net/manual/en/function.array-count-values.php
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
However, If you don't want to use that function, you can do an ugly way of for loop.
$arrayName = array(1,2,1,3,4,3,2,5);
$resultArray = array();
foreach($arrayName as $value) {
$resultArray[$value] = isset($resultArray[$value]) ? $resultArray[$value] + 1 : 1;
}
print_r($resultArray); // Array ( [1] => 2 [2] => 2 [3] => 2 [4] => 1 [5] => 1 )

Counting frequencies of array elements

Related

Why cant slice or something like that of my arrays with php

I have lot arrays and i want to only print number of 2 and first arrays
i use array_slice but there is still a problem
Arrays:
Array
(
[0] => 441
[1] => Awesome
)
Array
(
[0] => 570
[1] => Noons
)
Array
(
[0] => 571
[1] => Roods
)
I need to like this:
Array
(
[0] => 441
[1] => Awesome
)
Array
(
[0] => 570
[1] => Noons
)
Basically you seem to only need:
array_slice(array_unique(array_column($Myarrays, 'nidtitle')), 0, 2);
This should be done instead of the entire code you use to generate the arrays.
Short explanation:
array_column will get the element nidtitle from each "row" (array entry) in $Myarrays
After that we run that column through a unique function
Then we get the first 2 elements with an array_slice
This should do the job:
$finalarray = array_slice($Myarray, 0, 2);
print_r($finalarray);
You can use array_slice to get the items you want.
$arr = array(Array(441,"Awesome"),
Array(570,"Noons"),
Array(571,"Roods"));
$two = array_slice($arr, 0,2);
Var_dump($two);
Array_slice second parameter is where the slice should start.
Third parameter is count of values to slice.
https://3v4l.org/NPcJT

print the array when it is exploded

In the below code i am getting the output
Array ( [0] => 1 [1] => 2 )
but the expected output is
Array ( [0] => 1 [1] => 2 [2] => 3) Array ( [0] => 1 [1] => 2 )
why is it always executing the second if condition? although the first condition is also true.
this is the code I have tried
<?php
$test_arr=array();
$temp_option_arr=array();
$option_arr=array();
$options_array_val = Array ( 0 => "animals:1", 1 => "animals:2", 2 => "animals:3", 3 => "birds:1", 4 => "birds:2" );
foreach($options_array_val as $options_val)
{
$search_filter = explode(":", $options_val);
print_r($search_filter);
if(!in_array($search_filter[0],$option_arr))
{
array_push($temp_option_arr,$search_filter[1]);
array_push($option_arr,$search_filter[0]);
$temp_option_arr=array();
}
array_push($temp_option_arr,$search_filter[1]);
}
$test_arr[$search_filter[0]]=$temp_option_arr;
$find_species = array();
if(!empty($test_arr['animals']))
{
$find_species = $test_arr['animals'];
print_r($find_species);
}
if(!empty($test_arr['birds']))
{
$find_species = $test_arr['birds'];
print_r($find_species);
}
?>
The line
$test_arr[$search_filter[0]]=$temp_option_arr;
is out of the foreach scope, therefore it only sets the array for the birds and not for the animals, so you need to move it one line upper.
Also, you assign temp_option_arr to a value
array_push($temp_option_arr,$search_filter[1]);
then set it back to empty array without using it
$temp_option_arr=array();
You can remove the first one I guess
You clear $temp_option_arr in the first part of your code, so it will have nothing that concerns animals by the time you exit the first loop.
But instead of using all these different arrays, just build an associative array keyed by the species (animals, birds, ...), and with as values the arrays of IDs (1, 2, 3, ... i.e., the parts after the :):
foreach($options_array_val as $options_val) {
list($species, $id) = explode(":", $options_val);
$option_arr[$species][] = $id;
}
After this loop the structure of $option_arr is this:
Array (
"animals" => Array (1, 2, 3)
"birds" => Array (1, 2)
)
I think you can do what you want with that. For instance to only get the animals:
$option_arr["animals"]
which is:
Array (1, 2, 3)

How can I get all array elements, where the value only occurs once in the array?

I'm trying to get all array elements, where the value only occurs once in the array.
I tried to use:
array_unique($array);
But this does only remove the duplicates, which is not what I want.
As an example:
$array = 0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
5 => 2
6 => 3
7 => 4
8 => 5
Expected output:
array(
0=>1
)
As you can see only the value 1 occurs once in the array, all other values are more than once in the array. So I only want to keep that one element.
This should work for you:
First use array_count_values() to count how many times each value is in your array. This will return something like this:
Array (
[1] => 1
[2] => 2
[3] => 2
[4] => 2
[5] => 2
// ↑ ↑
// Value Amount
)
After that you can use array_filter() to only get the values, which occurs once in your array. Means:
Array (
[1] => 1
[2] => 2
[3] => 2
[4] => 2
[5] => 2
)
And at the end simply use array_keys() to get the value from the original array.
Code:
<?php
$arr = [1,2,3,4,5,2,3,4,5];
$result = array_keys(array_filter(array_count_values($arr), function($v){
return $v == 1;
}));
print_r($result);
?>
output:
Array (
[0] => 1
)
You can use array_count_values to get the number of times each value exists in the array. You can use this to get all the values that occur only once by looking at the value in the returned array.
If you already have an array and it is in the structure described above, you should be able to just array_search(1, $array) and it will give you the key of the array with the value of 1. Or if you expect to have multiple keys with the value of 1, you can use array_keys($array, 1) and it will return an array of keys that have the value of 1. Hope this helps.

Getting Values from MultiDimensional array

My Array shown as follows:
Array
(
[0] => Array
(
[amount_id] => 1
[enquiry_id] => 1
[project_id] => 1
)
[1] => Array
(
[amount_id] => 4
[enquiry_id] => 4
[project_id] => 4
)
[2] => Array
(
[amount_id] => 5
[enquiry_id] => 5
[project_id] => 5
)
)
This Array can be increase. How can i get value of each 'amount_id' from this array? What function should i use? Can for each function will work?
Just try with:
$input = array( /* your data */ );
$output = array();
foreach ($input as $data) {
$output[] = $data['amount_id'];
}
You can use a one-liner array_walk() to print those..
array_walk($arr,function($v){ echo $v['amount_id']."<br>";});
Working Demo
Do like this in array_map or Use array_column for The version PHP 5.5 or greater
$outputarr= array_map(function($item){ return $item['amount_id'];},$yourarr);
print_r($outputarr);
Try the following, this is accessing the specific array - easier to debug later on and better speed:
$num=count($your_array);
for($i="0"; $i<$num; $i++)
{
echo $your_array[$i]['amount_id'];
}
you could loop until $i < count($your_array) but it means that the count will run in every loop, for high performance sites I wouldn't do it.
you could access a specific element in a 2D array by $your_array[$the_index]['amount_id'] or other index.

PHP Multidimensional Array First Object

I have an array in PHP that looks like
Array ( [123654] => Array ( [0] => 123456789123456789 [1] => 1 [2] => 06/24/2011 [3] => 06/24/2012 [4] => 12355.44 [5] => 55321.55 ) )
I know in javascript I could access the data I need by doing array[0][0], how would I go about doing this in PHP. It is the 123456789123456789 value that I'm looking at getting.
Try this
array_slice($array, 0, 1);
http://php.net/array_slice
If you don't know the exact keys, you could do something like this:
$a = array_values($my_array);
$b = array_values($a[0]);
echo $b[0];
array_values replaces the keys by simple numbers from 0 to n-1 (where n is the count of values), by that you can access your desired value with the indexes [0][0]. See more here
http://codepad.org/YXu6884R
Here you go. See above for proof. The methodology from #azat is not explicit enough and is prone to risk if the elements of the array or sub array are re-arranged or if the key value for the super array changes.
$my_array = array( 123654 => array( 0 => '123456789123456789', 1 => '1', 2 => '06/24/2011', 3 => '06/24/2012', 4 => '12355.44', 5 => '55321.55' ) );
echo $my_array['123654'][0];
Try
$first = array_shift(array_values($array));
http://php.net/manual/en/function.array-shift.php

Categories