new in php

I want to find a number of times a character is repeated in a array and in what position

ex. $tbl1=array(1,2,3,1,4,5,6,3,1,2,​5,6,7,8,3,4,5,6,3) how many times repeated the “3” and what position

Hi,

[php]$tbl1 = array(1,2,3,1,4,5,6,3,1,2,5,6,7,8,3,4,5,6,3);

$result = array();

foreach ($tbl1 as $value) {
if (isset($result[$value])) {
$result[$value]++;
} else {
$result[$value] = 1;
}
}

print_r($result);[/php] output Array ( [1] => 3 [2] => 2 [3] => 4 [4] => 2 [5] => 3 [6] => 3 [7] => 1 [8] => 1 )

thanks for the help but I want “many times there is 3 and in what positions” the code you wrote me brings a lot of rectifications exist for every number of the array

Array ( [1] => 3 [2] => 2 [3] => 4 [4] => 2 [5] => 3 [6] => 3 [7] => 1 [8] => 1 )

make a function that takes a list of numbers and a value to search for. loop over the list and check if the current number matches the value searched for. if so store the position in a results array. then you can just count the results array to get the number of times the value is used, and use the values of the results array for the positions

but I want "many times there is 3 and in what positions"
oh... ok :)

[php]$tbl1 = array(1,2,3,1,4,5,6,3,1,2,5,6,7,8,3,4,5,6,3);

$result = array();

foreach ($tbl1 as $i => $value) {
if (isset($result[$value])) {
$result[$value][‘times’]++;
$result[$value][‘position’][] = $i;
} else {
$result[$value] = [‘times’ => 1, ‘position’ => [$i]];
}
}

print_r($result[3]);[/php]

[code]Array
(
[times] => 4
[position] => Array
(
[0] => 2
[1] => 7
[2] => 14
[3] => 18
)

)
[/code]

thank you very much
will try it

Here’s my take :
[php]<?php
$number = 3;
$tbl1 = array(1,2,3,1,4,5,6,3,1,2,5,6,7,8,3,4,5,6,3);
$result = []; // New way of writing array():

foreach ($tbl1 as $key => $value) {
if ($value === $number) {
$result[] = $key;
}
}
echo "The number " . $number . " appears " . count($result) . " times and here are the positions in the array
";
echo “

” . print_r($result, 1) . “
\n”;[/php]

thank you very much

Why are people giving working code? The algorithm is one thing, but just handing over something? How does that help anyone learn?

I would have to agree.

All the old faces in here.
Afternoon Jim, Strider, Aston, Kevin… 8)

Nice to see ya’ll still around.
Take care and have a good new year. :wink:

PS: Sorry for hijacking the thread! :stuck_out_tongue: :stuck_out_tongue:

Sponsor our Newsletter | Privacy Policy | Terms of Service