art art - 4 months ago 12
PHP Question

Set element inside array of array

If the 3rd element of array inside cars array is true i want to set others to be true .How to achieve it?

<?php
$cars = array
(
array(1,1,'f'),
array(2,2,'f'),
array(3,3,'t'),
array(4,4,'f')
);

foreach($cars as $keys){
if($keys[2]=='t')
$count=1;
}

foreach($cars as $keys){
if($count==1)
$keys[2] = 't';
}
print_r($cars);
?>

Answer

Just change 2 things as described below, Try:

$cars = array
  (
  array(1,1,'f'),
  array(2,2,'f'),
  array(3,3,'t'),
  array(4,4,'f')
  );
$count = 0; // declare $count
foreach($cars as $keys){
    if($keys[2]=='t')
        $count=1;
}
foreach($cars as $key=>$keys){
  if($count==1)
     $cars[$key][2] = 't'; // change value to t like this
}

output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 1
            [2] => t
        )

    [1] => Array
        (
            [0] => 2
            [1] => 2
            [2] => t
        )

    [2] => Array
        (
            [0] => 3
            [1] => 3
            [2] => t
        )

    [3] => Array
        (
            [0] => 4
            [1] => 4
            [2] => t
        )

)