Forum Moderators: coopster

Message Too Old, No Replies

array problem

         

omoutop

1:20 pm on Apr 6, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Hello all,

let's say we have an array like this one:
$my_array = array("a"=>"1", "b"=>"2", "c"=>"3");
// the pairs are $my_name=>$my_number

In our example 1,2,3 are numbers (counts, ids, timestamps etc), and they are all integers.

I want a way to find a partiular name in the array and increase it's value by 1 (or by any other integer number).

So in my example:


foreach ($my_array as $my_name=>$my_number)
{
// loop to find $my_name - easily done
// increase $my_number by 1 inside the array
// so in the next loop i will have the increased value
// no idea how to do this so far
}

Is there a build-in function in php or i write something of my own?

Robber

2:53 pm on Apr 6, 2006 (gmt 0)

10+ Year Member



I'm not 100% sure I'm with you here, but if you are looking to increment the value stored against a key you should be able to do something like:

$my_array[$name]++;

Birdman

8:06 pm on Apr 6, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Robber is correct, except it should read:

$my_array[$my_name]++;

Expanding on that, here is an even easier way to do the same thing. Here, no loop is needed. I assume you have your search value already in a var. Simply change $search to your var name.

if ( array_key_exists( $search, $my_array ) ) {$my_array[$search]++;}

omoutop

7:55 am on Apr 7, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Thanks both for your insight.
Problem solved but with isset() instead of array_key_exists().