8

I'm relearning PHP, so sorry for might be a basic question. I can't find an answer.

I have a multidimensional array, I need to replace the value for a specific key (all instances of) with another value.

Array ( 
    [13] => Array ( 
                [ad_id] => 13 
                [ad_name] => Qhxxst 
                [ad_link] => www.qxxst.co.uk 
                [ad_type] => 1 
            ) 
    [15] => Array ( 
                [ad_id] => 15 
                [ad_name] => Pxxly 
                [ad_link] => http://pixxly.net 
                [ad_type] => 1 
            ) 
    [16] => Array ( 
                [ad_id] => 16 
                [ad_name] => cxxm 
                [ad_link] => http://www.cxxm.co.uk 
                [ad_type] => 1 
            ) 
)

I wish to replace all instances of ad_type with another value. i.e. Where ad_type = 1, replace with x Where ad_type = 2, replace with y

I've been using str_replace and json_decode without success. They either replace all instances of '1' or nothing at all. I need to target ad_type keys only.

2 Answers 2

15
foreach($array as &$value) {
    $value['ad_type'] = 'new value';
}
1
  • 1
    Thank you. Using your example got it sorted. 'code' foreach($qresult as &$value) { $value['ad_type'] = str_replace ("1","Interstatial",$value['ad_type']); $value['ad_type'] = str_replace ("2","Top Frame",$value['ad_type']); }
    – Damo
    Commented Apr 24, 2011 at 14:09
5

Best way to access the keys and values of an array is with foreach loop.

Something like:

$array= Array ( [13] => Array ( [ad_id] => 13 [ad_name] => Qhxxst [ad_link] => www.qxxst.co.uk [ad_type] => 1 ) [15] => Array ( [ad_id] => 15 [ad_name] => Pxxly [ad_link] => http://pixxly.net [ad_type] => 1 ) [16] => Array ( [ad_id] => 16 [ad_name] => cxxm [ad_link] => http://www.cxxm.co.uk [ad_type] => 1 ) );

foreach ($array as $key=>$val) 
{
    if ($key=="ad_type" && $val==1) 
    {
        $val="x";
    }
    elseif ($key=="ad_type" && $val==2) 
    {
        $val="y";
    }
}

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

2
  • 2
    This answer clearly does not work. It you are to pursue this path you need a double loop. Take a look at sandbox.onlinephpfunctions.com/code/…
    – apokryfos
    Commented Jun 19, 2019 at 12:44
  • This method does not work in any multi dimension array. """foreach ($arrayName as &$value) { $value['ValueName'] = str_replace($value['ValueName'],encryptText($value['ValueName']),$value['ValueName']); }""" worked for me Commented Apr 12, 2020 at 7:47

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.