Reputation: 25
Hello I am stuck modifying a value in a PHP array.
echo '<pre>';
print_r($data);
echo '</pre>';
I have to change this value :
I dont have to use to the keys : 900 and 2200 cause the values can change... How can I process to replace the first value "1578" by another in my $data array ?
Thanks a lot :)
Upvotes: 0
Views: 907
Reputation: 78
You can use double foreach loop and than break immediately after you find the first value like this:
foreach($data as $key1 => $value1){
foreach($data[$key1] as $key2 => $value2){
$data[$key1][$key2] = $your_new_value;
break 2;
}
}
The 2 after the break statement means that you break out of both loops at the same time. Alternatively you can use array_keys which returns the keys of an array like this.
$key1 = array_keys($data)[0];
$key2 = array_keys($data[$key1])[0];
$data[$key1][$key2] = $your_new_value;
array_keys returns an array so the [0] at the end of the line means the first element of that array, because the first element of that array is usually the first key.
Upvotes: 0
Reputation: 125526
make a loop on your array like:
foreach ($data as $key => $arr)
{
$firstKey = array_search(1578, $arr);
# replace
if ($firstKey !== false)
$data[$key][$firstKey] = "my new value";
}
Upvotes: 0
Reputation: 179
You have to use nested loop.
foreach($data as $key => $value) {
foreach( $value as $k => $v ) {
if( $k === 0 ) {
$data[$key][$k] = 'some value here';
}
}
}
Upvotes: 1
Reputation: 131
You would change everytime the first value of your array or just the first "1578" of your array ?
If is the first case you can do : $data[900][array_key_first($data[900])] = $newValue;
Else you can search the key of the first 1578 and change it :
$key = array_search('1578', $data[900]);
$data[900][$key] = $newValue;
And if you want to change all the first 1578 in all your sub-array, loop on it
Upvotes: 0