Count variables from multidimensional array parts - php

I have a multidimensional array with emails
$emails = ( "emailid" => array( "email1", "email2" ,"email3" ) );
I want to count first part ($emails[]) of multi-dimension array and second part ($emails[][]). count($emails) only counts a whole array.
may be some one knows how.
Thank you!

You can use the COUNT_RECURSIVE flag to change how count works and get it to recursively count all items in your array regardless the depth. If you are just looking to get the count of the email addresses within the emailid sub array, you can access it directly by it's key.
$emails = ['emailid' => ['email1', 'email2', 'email3']];
// recursive count
echo count($emails, COUNT_RECURSIVE); // output 4
// normal count
echo count($emails); // output 1
// normal count using key
echo count($emails['emailid']); // output 3

What about this :
<?php
$emails = array("emailid" => array("email1","email2","email3"));
echo 'emails[] = ' . count($emails) . '<br />'; // result: 1
echo 'emails["emailid"] = ' . count($emails["emailid"]); // result: 3
?>

Related

How to decode an array?

I have this PHP array
$gender = array (
0 => array('Male','m.gif'),
1 => array('Female','f.gif'),
2 => array('Other','o.gif'),
);
And this ODBC
$DB = $core_db->Execute("SELECT ID, Name, Age, Location, Gender FROM Profiles
ORDER BY Name");
I want to use echo' . decode_gender($DB->fields[4], '2') . '; But I don't know how to make this decode function to connect that $DB->fields[4] is the same Gender from the array $gender in order to use it.
This function should do what you want. It takes the Gender value from the table lookup to index into the $genders array, and the second parameter to decide which value from the lookup array to return. Note that since you've said you want a value of 2 to return the second value in the array, you have to subtract one from the $idx value:
function decode_gender($gender, $idx) {
$genders = array (
0 => array('Male','m.gif'),
1 => array('Female','f.gif'),
2 => array('Other','o.gif'),
);
return $genders[$gender][$idx-1];
}
echo decode_gender(2, 2) . PHP_EOL;
echo decode_gender(1, 1) . PHP_EOL;
Output:
o.gif
Female
Demo on 3v4l.org

How to seprate numeric value from charcter using PHP

I need one help.i need to separate numeric value from character using PHP.I am explaining my code below.
$subcatid=a1,a2,4,5
here i have some value with comma separator i need here separate numeric value(i.e-4,5) first and push them into a array then i have to separate rest numeric value from character(i.e-1 from a1,2 from a2) and push those separated value into another array.Please help me.
Try this
<?php
$subcatid="a1,a2,4,5";
$subcatid_arr = explode(",",$subcatid);
$onlynum_subcatid = array_filter($subcatid_arr, 'is_numeric');
$onlynum = implode(",",$onlynum_subcatid );
echo "Only Number : ".$onlynum;
$notnum_subcatid = array_diff($subcatid_arr,$onlynum_subcatid );
$notnum = implode(",",$notnum_subcatid );
echo "\nNot Number : ".$notnum;
?>
Output is :
Only Number : 4,5
Not Number : a1,a2
check here : https://eval.in/539059
Use this code
$subcatid="a1,a2,4,5";
$strArray = explode(',',$subcatid);
$intArr = array();
foreach($strArray as $key=>$value):
if(preg_match('/^[0-9]*$/',$value)):
$intArr[]=$value;
else:
$str2Arr = str_split($value);
foreach($str2Arr as $keyStr=>$lett):
if(preg_match('/^[0-9]*$/',$lett)):
$intArr[]=$lett;
endif;
endforeach;
endif;
endforeach;
var_dump($intArr);
in this code you can expect your result. Do process with the $number, $char array as required
<?php
$subcatid="a1,a2,4,5";
$subcatid_arr = explode(",",$subcatid);
for($i=0;$i<sizeof($subcatid_arr);$i++){
if(is_numeric($subcatid_arr[$i])){
$number[]=$subcatid_arr[$i];
}
else{
$char[]=$subcatid_arr[$i];
}
}
print_r($number);// 4,5
print_r($char);// a1,a2
?>
If I am understanding correctly, you want to put all of the original numeric values into a single array and then filter just the numeric parts of the leftovers and put them in to a second array.
If this is correct then I believe this should do what you want.
<?php
$subcatid = 'a1,a2,4,5';
$subcat_array = explode(",",$subcatid);
$subNums1 = [];
$subNums2 = [];
foreach($subcat_array as $item) {
if(is_numeric($item)) {
// This pushes all numeric values to the first array
$subNums1[] = $item;
} else {
// This strips out everything except the numbers then pushes to the second array
$subNums2[] = preg_replace("/[^0-9]/","",$item);
}
}
print_r($subNums1);
print_r($subNums2);
?>
This will return:
Array (
[0] => 4
[1] => 5
)
Array (
[0] => 1
[1] => 2
)

PHP Multidimensional Array Length

This is a multidimensional PHP array.
$stdnt = array(
array("Arafat", 12210261, 2.91),
array("Rafat", 12210262, 2.92),
array("Marlin", 12210263, 2.93),
array("Aziz", 12210264, 2.94),
);
I can find out the length of the array. That means
count($stdnt); // output is 4
[
array("Arafat", 12210261, 2.91),
array("Rafat", 12210262, 2.92),
array("Marlin", 12210263, 2.93),
array("Aziz", 12210264, 2.94)
] `
But can't get the internal array length.
How can I ?
If you are assuming the subarrays are all the same length then:
$count = count($stdnt[0]);
If you don't know the keys:
$count = count(reset($stdnt));
To get an array with a separate count of each of the subarrays:
$counts = array_map('count', $stdnt);
The other way to count internal array lengths is to iterate through the array using foreach loop.
<?php
$stdnt = array(
array("Arafat", 12210261, 2.91),
array("Rafat", 12210262, 2.92),
array("Marlin", 12210263, 2.93),
array("Aziz", 12210264, 2.94),
);
foreach($stdnt as $s)
{
echo "<br>".count($s);
}
?>
please use sizeof function or count function with recursive
e.g echo (sizeof($stdnt,1) - sizeof($stdnt)) ; // this will output you 9 as you want .
first sizeof($stdntt,1) ; // will output you 13 . count of entire array and 1 mean recursive .
According to the hint from Meaning of Three dot (…) in PHP, the following code is what I usually use for this case:
$stdnt = array(
array("Arafat", 12210261, 2.91),
array("Rafat", 12210262, 2.92),
array("Marlin", 12210263, 2.93),
array("Aziz", 12210264, 2.94),
);
echo count(array_merge(...$stdnt));
The Splat operator "..." will only work,
Only if the first level keys are in integer, ie, not "strings"
PHP > 5.6
// You may try as per this sample
$cars=array(
array("volvo",43,56),
array("bmw",54,678)
);
$mySubSize=sizeof($cars);
for ($i=0;$i<$mySubSize;$i++) {
foreach ($cars[$i] as $value) {
echo "$value <br>";
}
}

php array_rand function with foreach

This code picks 2-6 pitches from the $vec array. I'd like to echo out each individual pitch, but interestingly enough, it gives me the numeric values of the placement of the pitch in the array (ie: 2 5 6 instead of D F F#)
$pick = rand(2,6);
$vec = array("C","C#","D","D#","E","F","F#","G","G#","A","A#","B");
$random_keys = array_rand($vec,$pick);
foreach ($random_keys as $pitch){
echo $pitch; echo "<br>";
}
Why is it doing this and how can I get the pitches instead of the numbers?
Try this:
$pick = rand(2,6);
$vec = array("C","C#","D","D#","E","F","F#","G","G#","A","A#","B");
$random_keys = array_rand($vec, $pick);
foreach ($random_keys as $key) {
echo $vec[$key], '<br />';
}
From array_rand() documentation:
Return value
If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.

How to build a bidimensional array in PHP?

I am trying to push values onto an array like so:
$scoreValues[$i][] = $percent ;
$scoreValues[$i][] = '<span id="item'.$i.'" class="suggestElement" data-entityid="'.$row['id'].'" data-match="'.$percent.'">'.rawurldecode($row['name']).'</span>' ;
I basically want to link together the $percent with the string, so I get an output like:
array (0 > array('46.5', '<span etc etc')
I then plan to sort by the percent sub-array so I have the highest scoring strings at the top.
Simplest way would be to use two arrays :
$percents[$i] = $percent;
$scores[$i] = "<span....>");
Or one array, but indexed like this
$data = new arrray('percents' => array(), 'scores' => array());
$data['percents'][$i] = $percent;
$data['scores'][$i] = "<span....>");
Once this is done, you then sort your arrays using array_multisort :
array_multisort(
$data['percents'], SORT_DESC,
$data['scores']);
In the second line you need to specify the index of the second array:
$scoreValues[$i][$j] = '<span id="item'.$i.'" class="suggestElement" data-entityid="'.$row['id'].'" data-match="'.$percent.'">'.rawurldecode($row['name']).'</span>' ;
So you basically need 2 counters, one for the external array ($i) and on for the internal array ($j).
EDIT:
You got me a bit confused with the question, seems like what you need is not a multi dimensinal array but rather a simple array:
$scoreValues[$percent] = '<span id="item'.$i.'" class="suggestElement" data-entityid="'.$row['id'].'" data-match="'.$percent.'">'.rawurldecode($row['name']).'</span>' ;
Please note that this requires $percent to be unique.
Try this:
$val = array(
'percent' => $percent,
'html' => '<span id="item' . $i .
'" class="suggestElement" data-entityid="'.$row['id'].
'" data-match="'.$percent.'">'.rawurldecode($row['name']).
'</span>'
);
// This just pushes it onto the end of the array
$scoreValues[] = $val ;
// Or you can insert it at an explicit location
//$scoreValues[$i] = $val;

Categories