0

I'm trying to read a file line by line and store values to an array. and if a username already in the array occurs update existing array for the username, if not create new array.

$data[] = array('username1'=>array('failed-attempts'=>'0','ip'=>array('191.25.25.214'))); 

$data[] = array('username2'=>array('failed-attempts'=>'0','ip'=>array('221.25.25.214')));  

I'm trying to update failed-attempts value and add a newip address to ip array if array for username exists.

I tried this

foreach($data as $d){
    if (array_key_exists($username, $d)) {
           //username is already in the array, update attempts and add this new IP.


    }else{

        $data[] = array('username3'=>array('failed-attempts'=>'0','ip'=>array('129.25.25.214')));  //username is new, so add a new array to $data[]

    }
}

How do I update an existing array?

2 Answers 2

1

something like this should work:

foreach($data as $key => $d){
    if (array_key_exists($username, $d)) {
        $data[$key][$username]['ip'] = array("your_ip_value");
    } else {
        ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1
<?php

$result = array();
foreach($data as $d){

    $ip = ''; // get the ip, maybe from $d?
    $username = ''; // get the username

    // if exist, update
    if (isset($result[$username])) {
        $info = $result[$username];
        $info['failed-attempts'] += 1;
        $info['ip'][] = $ip;

        $result[$username] = $info;
    } else {
        $info = array();
        $info['failed-attempts'] = 0;
        $info['ip'] = array($ip);
        $result[$username] = $info;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.