0

I'm not sure how to better phrase my question, but here is my situation.

I have an array like the following:

$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");

I need to loop through this array and try to match the first portion of each string in the array

e.g.

$id          = "222222";
$rand_number = "999888";
if ($id match the first element in string) {
     fetch this string
     append "999888" to "122874|876394|120972"
     insert this string back to array
}

So the resulting array becomes:

$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-999888|122874|876394|120972", "333333-Name3-122874|876394|120972");

Sorry if my question appears confusing, but it really is pretty difficult for me to even grasp some of the required operations.

Thanks

4
  • purely based on the above - foreach() loop, substr() to match then create a new output array appended extra data. Commented Sep 25, 2014 at 3:43
  • 2
    append or prepend? you said one but your example shows the other? Commented Sep 25, 2014 at 3:52
  • Sorry for the confusion, prepend or append is actually both fine in my case Commented Sep 25, 2014 at 3:53
  • i think all 3 of us have a version of right - pick one :-) Commented Sep 25, 2014 at 3:54

4 Answers 4

2

Try this:

$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id          = "222222";
$rand_number = "999888";

// Loop over each element of the array
// For each element, $i = the key, $arr = the value
foreach ($temp_array as $i => $arr){

    // Get the first characters of the element up to the occurrence of a dash "-" ...
    $num = substr($arr, 0, strpos($arr, '-'));

    // ...and check if it is equal to $id...
    if ($num == $id){
        // ...if so, add $random_number to the back of the current array element
        $temp_array[$i] .= '|'  . $rand_number;
    }
}

Output:

Array
(
    [0] => 111111-Name1-122874|876394|120972
    [1] => 222222-Name2-122874|876394|120972|999888
    [2] => 333333-Name3-122874|876394|120972
)

See demo

Note: As Dagon pointed out in his comment, your question says appends, but your example shows the data being prepended. This method appends, but can be altered as necessary.


http://php.net/manual/en/control-structures.foreach.php

http://php.net/manual/en/function.substr.php

http://php.net/manual/en/function.strpos.php

Sign up to request clarification or add additional context in comments.

5 Comments

thanks a ton for the reply, I tried your code and it works great, but I would really like to better understand this code. Are you able to provide a little explanation? Thanks :)
@user2028856 I've added some comments to the code that might help explain it a little.
What does the .= symbol mean? I've seen it elsewhere but couldn't find out what it means
@user2028856 It's for string concatenation; it appends to the string rather than overwriting it. If $x = 'hello', and you said $x .= 'world', then $x would contain helloworld. Consider this demo
2

You could also using some exploding in this case too:

$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
foreach($temp_array as &$line) {
                    // ^ reference
    $pieces = explode('|', $line); // explode pipes
    $first = explode('-', array_shift($pieces)); // get the first part, explode by dash
    if($first[0] == $id) { // if first part is equal to id
        $first[2] = $rand_number; // replace the third part with random
        $first = implode('-', $first); // glue them by dash again
        $line = implode('|', array($first, implode('|',$pieces))); // put them and glue them back together again
    }
}
echo '<pre>';
print_r($temp_array);

2 Comments

This code works also well, except that I don't want to replace the third part with random, I just want to append the new random number to the existing random number string
@user2028856 actually, looking at the resultant array, it seems that that part is replaced by the random, so the real intent really is to append/push it on the end when the match occurs
2

crude answer - its going to depend on the expected values of the initial ids. if they could be longer or shorter then explode on the hyphen instead of using substr

    $temp_array = array("111111-Name1-122874|876394|120972","222222-Name2-122874|876394|120972","333333-Name3-122874|876394|120972");

    $id = "222222";
    $rand_number = "999888";

    foreach($temp_array as $t){
        if(substr(0,6,$t)==$id){
            $new[] = $t.'|'.$rand_number;
        }else{
            $new[] = $t;
        }
    }

Comments

2

Another version using array_walk

$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");

$id          = "222222";
$rand_number = "999888";
$params = array('id'=>$id, 'rand_number'=>$rand_number);
array_walk($temp_array, function(&$value, $key, $param){
    $parts = explode('-', $value); // Split parts with '-' so the first part is id
    if ($parts[0] == $param['id']){
        $parts[2]="{$param['rand_number']}|{$parts[2]}"; //prepend rand_number to last part
        $value=implode('-',$parts); //combine the parts back
    }
},$params);

print_r($temp_array);

If you just want to append The code becomes much shorter

$params = array('id'=>$id, 'rand_number'=>$rand_number);
array_walk($temp_array, function(&$value, $key, $param){
    // here check if the first part of the result of explode is ID 
    // then append the rand_number to the value else append '' to it.
    $value .= (explode('-', $value)[0] == $param['id'])? "|{$param['rand_number']}" : '';
},$params);

Edit: Comments added to code.

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.