I know how to loop through equal arrays like this
foreach( $codes as $index => $code ) {
echo 'The Code is '.$code;
echo 'The Name is '.$names[$index];
}
Not sure how to loop through these 2 arrays and still manage to get all values when both arrays have different number of elements.
$code = array(R9,R10,R11,R12);
$names = array(Robert,John,Steve,Joe,Eddie,Gotham);
...how to loop through these 2 arrays and still manage to get all values when both arrays have different number of elements.
You can use for loop for this.
The solution is:
Take length of the longest array as the condition for for loop.
Use array_key_exists() function to check whether the index exists in the particular array or not, and display the element accordingly.
So your code should be like this:
$code = array("R9","R10","R11","R12");
$names = array("Robert","John","Steve","Joe","Eddie","Gotham");
$maxLength = count($code) > count($names) ? count($code) : count($names);
for($i = 0; $i < $maxLength; ++$i){
echo array_key_exists($i, $code) ? 'The Code is '. $code[$i] : "";
echo array_key_exists($i, $names) ? ' The Name is '. $names[$i] : "";
echo "<br />";
}
Output:
The Code is R9 The Name is Robert
The Code is R10 The Name is John
The Code is R11 The Name is Steve
The Code is R12 The Name is Joe
The Name is Eddie
The Name is Gotham
Related
I have the following array:
$array = [2,2,5,2,2];
I would like to get the number which is different from the others, for example all the numbers are 2 except the number 5. So Is there anyway to get the different number using any array method or better solution? My solution is:
$array = [2,2,5,2,2];
$array1 = [4,4,4,6,4,4,4];
$element = -1;
$n = -1;
$count = 0;
for($i=0; $i<count($array1); $i++) {
if($element !== $array1[$i] && $element !== -1 & $count==0) {
$n = $array1[$i];
$count++;
}
$element = $array1[$i];
}
dd($n);
You can use array_count_values for group and count same value like:
$array = [2,2,5,2,2];
$countarray = array_count_values($array);
arsort($countarray);
$result = array_keys($countarray)[1]; // 5
Since you only have two numbers, you will always have the number with the least equal values in second position
Reference:
array_count_values
array_keys
A small clarification, for safety it is better to use arsort to set the value in second position because if the smallest number is in first position it will appear as the first value in the array
Sorting Arrays
You can user array_count_values which returns array with item frequency.
Then use array_filter to filter out data as follow:
$arrayData = [2,2,2,5];
$filterData = array_filter(array_count_values($arrayData), function ($value) {
return $value == 1;
});
print_r($filterData);
Inside array_filter(), return $value == 1 means only get the data with 1 frequency and thus filter out the other data.
<?php
function UniqueAndDuplicat($array){
$counts = array_count_values($array);
foreach ($counts as $number => $count) {
print $number . ' | ' . ($count > 1 ? 'Duplicate value ' : 'Unique value ') . "\n";
}
}
$array1 = [2,2,5,2,2];
$array2 = [4,4,4,6,4,4,4];
UniqueAndDuplicat($array1);
//output: 2 | duplicate value 5 | Unique value
UniqueAndDuplicat($array2);
//output: 4 | duplicate value 5 | Unique value
?>
Use this function to reuse this you just call this function and pass an Array to this function it will give both unique and duplicate numbers.
If you want to return only Unique number then use the below code:
<?php
function UniqueAndDuplicat($array){
$counts = array_count_values($array);
foreach ($counts as $number => $count) {
if($count == 1){
return $number;
}
}
}
$array1 = [2,2,5,2,2];
$array2 = [4,4,4,6,4,4,4];
echo UniqueAndDuplicat($array1); // 5
echo "<br>";
echo UniqueAndDuplicat($array2); // 6
?>
This question already has answers here:
Selecting multiple array elements
(3 answers)
Closed 1 year ago.
Hey GUys Im beginner to php programming here here i have 15 element in array . i want to display first 4 array element in first line and then second 4 array of element in nextline . i dont know how to achive it here is my code help me on this. thanks in advance
<?php
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
echo $nr_elm = count($arry); // gets number of elements in $arry
$nr_col = 4; // Sets the number of text Per Line
// If the array has elements
if ($nr_elm > 0)
{
// Traverse the array with FOR
for($i=0; $i<$nr_elm; $i++)
{
echo $textInLine= $arry[$i]. ' | ';
// If the number of columns is completed for a line (rest of division of ($i + 1) to $nr_col is 0)
// Closes the current line, and begins another line
$col_to_add = ($i+1) % $nr_col;
if($col_to_add == 0) { $textInLine .= '/n'; }
}
}
echo $textInLine;
?>
Use array_chunk for this:
$array = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$size = 4;
foreach (array_chunk($array, $size) as $chunk) {
echo implode(' ', $chunk) . PHP_EOL;
}
Another solution without using array_chunk is using modulo:
$array = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$size = 4;
$counter = 0;
foreach ($array as $character) {
echo $character;
// echo new line after every 4th character, a space after the others
echo (++$counter % $size === 0) ? PHP_EOL : ' ';
}
Chunk the array and implode the items in the chunk.
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$chunks = array_chunk($array, 4);
foreach($chunks as $chunk){
echo implode(" ", $chunk) . "</br>\n";
}
Array_chunk splits the array in to pieces of the size you define.
The resulting array is multidimensional with the items in the subarray.
Implode takes the items in the subarray and adds the delimiter (" ") in between each item and makes it a string.
Use array_chunk, it will Split an array into chunks
<?php
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$arr = array_chunk($arry, 4, true);
foreach($arr as $value) {
echo implode(' ', $value) . PHP_EOL ;
}
?>
I don't know if the "15" is intentional, but if you want to remove it just remove the "echo".
I also recommend to use empty() to verify if your array is empty or not, just like this :
if (!empty($arry)) { //Code }
(notice the "!")
Now, for your main question what I would do is using a variable which increments up to 4, then you insert a line break with echo <br>; and reset the variable to 0.
The code should look something like this :
$c = 0;
for($i=0; $i<$nr_elm; $i++)
{
echo $arry[$i];
$c ++;
if ($c >= 4) {
echo "<br>";
$c = 0;
}
}
I hope this helped you
In the first time, I'm sorry for my disastrous english.
After three days trying to solve this, i give up.
Giving this array:
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" )
I have to extract the full name of the higher first stringlength word of each full name.
In this case, considering this condition Benjamin will be the higher name. Once
this name extracted, I have to print the full name.
Any ideas ? Thanks
How about this?
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" );
if (count($names) > 0)
{
$higher_score = 0;
foreach ($names as $name_key => $name_value)
{
$name_array = explode(" ", $name_value);
// echo("<br><b>name_array -></b><pre><font FACE='arial' size='-1'>"); print_r($name_array); echo("</font></pre><br>");
$first_name = $name_array[0];
// echo "first_name -> ".$first_name."<br>";
$score = strlen($first_name);
// echo "score -> ".$score."<br>";
if ($score > $higher_score)
{
$higher_score = $score;
$winner_key = $name_key; }
}
reset($names);
}
echo("longest first name is ".$names[$winner_key]." with ".$higher_score." letters.");
As said before, you can use array_map to get all the lenghts of the first strings, and then get the name based on the key of that value.
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" );
$x = array_map(
function ($a) {
$x = explode (" ", $a); // split the string
return strlen($x[0]); // get the first name
}
, $names);
$maxs = array_keys($x, max($x)); // get the max values (may have equals)
echo $names[$maxs[0]]; // get the first max
-- EDIT
Actually, there is a better way of doing this, considering this case. You can simply order the array by the lenght of the first names, and then get the first key:
usort($names,
function ($a, $b) {
$aa = explode(" ", $a); // split full name
$bb = explode(" ", $b); // split full name
if (strlen($aa[0]) > strlen($bb[0])){
return 0; // if a > b, return 0
} else {
return 1; // else return 1
}
}
);
echo $names[0]; // get top element
Allow me to provide a handmade solution.
<?php
$maxLength = 0;
$fullName = "";
$parts = array();
foreach($names as $name){
/* Exploding the name into parts.
* For instance, "James Walter Case" results in the following array :
* array("James", "Walter", "Case") */
$parts = explode(' ', $name);
if(strlen($parts[0]) > $maxLength){ // Compare first length to the maximum.
$maxLength = strlen($parts[0]);
$fullName = $name;
}
}
echo "Longest first name belongs to " . $fullName . " (" . $maxLength . " character(s))";
?>
Basically, we iterate over the array, split each name into parts (delimited by spaces), and try to find the maximum length among first parts of names ($parts[0]). This is basically a maximum search algorithm.
There may be better ways with PHP array_* functions, but well, this one gets pretty self-explanatory.
You can try something like..
$maxWordLength=0;
$maxWordIndex=null;
foreach ($names as $index=>$name){
$firstName=first(explode(' ',$name));
if (strlen($firstName)>maxWordLength){
$maxWordLength=strlen($firstName);
$maxWordIndex=$index;
}
}
if ($maxWordIndex){
echo $names[$maxWordIndex];
}
Is it possible to use a for loop where $i is part of the variable name? I'm trying to get this for loop to list the fruits:
$item1name = "apple";
$item2name = "orange";
$item3name = "banana";
for($i=0, $i<2, $i++) {
echo = "<li>$item?????</li>";
}
// should result in:
// <li>apple</li><li>orange</li><li>banana</li>
I realize I can put the fruits in an $itemname array and easily echo $itemname[$i], but that isn't what I'm asking. Is it possible to do this when $i is part of the variable name?
It is possible with the use of variable variables:
for($i=1; $i<=3; $i++) {
echo "<li>" . ${'item'.$i.'name'} . "</li>";
}
Note that your original code wasn't syntactically correct. I've fixed it. Also note how $i value changed. Your variable numbers are from 1 to 3, not 0 to 1.
But I don't see why you'd want this. Simply use an array instead.
Demo
I don't speak very good English, not sure about title so will try to explain what i need to do:
I am making log parser.
I have 3 dynamic arrays (read from .log file) containing corresponding elements:
$personName //array of strings, can contain same name
$itemName //array of strings, can contain same name
$itemAmount //array of numbers
Sample arrays:
$personName = array("Adam", "Maria", "Adam", "Adam");
$itemName = array("paper", "paper", "pen", "paper");
$itemAmount = array(11, 25, 2, 64);
I would like to sort (by person and item) and count (by amount) those arrays, eg. to print:
Total there are '100' 'paper' and '2' 'pen'.
'Adam' have '75' 'paper' and '2 'pen'.
'Maria' have '25' 'paper'.
This would allow me to get % of each item each person have, eg.:
'Adam' have '75'% of all 'paper' and '100'% of all 'pen'.
'Maria' have '25'% of all 'paper'.
I have arrays with unique names:
$persons = array_keys (array_flip ($personName));
$items = array_keys (array_flip ($itemName));
I did tried different combinations of for loops with foreach, but I struggle to find any solution.
Can somebody help me to get right approach?
(sorry if this is too basic, i really tried to look for solution and I'am very new to programming, started learning 3 days ago with this project)
Thanks!
Like this:
<?php
$personName = array("Adam", "Maria", "Adam", "Adam", "Mihai");
$itemName = array("paper", "paper", "pen", "paper", 'pencil');
$itemAmount = array(11, 25, 2, 64, '18');
$items = array();
$persons = array();
foreach($itemName as $id => $name){
$items[$name] += $itemAmount[$id]; // we are adding amount for each item to $items array
$persons[$personName[$id]][$name] += $itemAmount[$id]; // we are adding every item with amount to each persons
}
echo "Total there are "; // we are looping in each $items to display totals
$i = 0;
foreach($items as $nr => $item){
echo "'".$item."' '".$nr."'";
if($i < count($items)-2){ // this is for 'and' or ',' in case of multiple items
echo ", ";
} elseif($i < count($items)-1){
echo " and ";
}
$i++;
}
echo '<br />';
foreach($persons as $one => $value ){ // we are looping in each persons to display what they have
echo "'".$one."' have ";
$i = 0;
foreach($value as $val => $number){
echo "'".$number."' '".$val."'";
if($i < count($value)-2){ // this is for 'and' or ',' in case of multiple items
echo ", ";
} elseif($i < count($value)-1){
echo " and ";
}
$i++;
}
echo '.<br />';
}
// print_r($items); // will result in all items
// print_r($persons); // will result in every person with every item
?>
Now you can manage %.