0

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);
   ?>
3
  • 1
    Why do you use a string named "f" and a strnig named "t" instead of the boolean values true and false? Commented Jul 22, 2016 at 7:51
  • f and t were strings there not boolean types @Xatenev Commented Jul 22, 2016 at 7:56
  • Exactly, the question is why you use 'f' and 't' instead of true and false. Commented Jul 22, 2016 at 12:17

4 Answers 4

1

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
        )

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

Comments

1

You were almost close, Just make this change, use reference symbol & to actual change

from

foreach($cars as $keys){

to

foreach($cars as &$keys){

Check this : https://eval.in/609879

Comments

1
$exists= false;
foreach($cars as $car)
{
    if($car[2] == 't')
    {
        $exists= true;
    }
}

if($exists)
{
    for($i=0; $i<count($cars); $i++)
    {
        $cars[$i][2] = 't';
    }
}

Comments

0

Here's the solution for you

<?php

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

if(in_array('t', array_column($cars, 2))){
    $cars = array_map(function($v){
        $v[2] = 't';
        return $v;
    }, $cars);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.