Jacek Jagiełło
Jacek Jagiełło

Reputation: 223

Get first value from array

I have an PHP array that has saved users steps:

array(
    'step_1' => 1,
    'step_2' => 1,
    'step_3' => 0,
    'step_4' => 0,
    'step_5' => 0
);

So, my user do step_1, and step_2, but he don't do other steps. Now, i want to get name of first step that he don't do, it's "step_3" in this example.

But if array looks that:

 array(
    'step_1' => 1,
    'step_2' => 1,
    'step_3' => 1,
    'step_4' => 1,
    'step_5' => 0
);

I want to get "step_5", than i know that user don't do step_5 and i can, for exapmle redirect them to specify page. How can i get it?

Upvotes: 1

Views: 1171

Answers (3)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

You could use array_search()

See In Action

<?php 
$array = array(
    'step_1' => 1,
    'step_2' => 1,
    'step_3' => 1,
    'step_4' => 0,
    'step_5' => 0
);

$key = array_search(0, $array); // $key = step_4;

echo $key;
?>

Upvotes: 6

Baba
Baba

Reputation: 95101

You can try

$step = array(
    'step_1' => 1,
    'step_2' => 1,
    'step_3' => 0,
    'step_4' => 0,
    'step_5' => 0
);
var_dump(__missing($step));
var_dump($step);

Output

string 'step_3' (length=6)
array
  'step_1' => int 1
  'step_2' => int 1
  'step_3' => int 1
  'step_4' => int 0
  'step_5' => int 0

Example 2

$step = array(
    'step_1' => 1,
    'step_2' => 1,
    'step_3' => 1,
    'step_4' => 1,
    'step_5' => 1
);
var_dump(__missing($step));
var_dump($step);

Output

string 'step_1' (length=6)
array
  'step_1' => int 1
  'step_2' => int 0
  'step_3' => int 0
  'step_4' => int 0
  'step_5' => int 0

Function used

function __missing(&$array) {
    $left = array_filter($array, function ($var) {
        return ($var == 1) ? false : true;
    });
    if (! empty($left)) {
        $key = key($left);
        $array[$key] = 1;
        return $key;
    } else {
        array_walk($array, function (&$var) {
            return $var = 0;
        });
        $key = key($array);
        $array[$key] = 1;
        return $key;
    }
}

Upvotes: 0

CappY
CappY

Reputation: 1580

You can use reset($array);

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

Return Values

Returns the value of the first array element, or FALSE if the array is empty.

Edit:

You can use array_search(0,$array);

That will return you the key of first found var. (step_5) in your case.

Upvotes: 0

Related Questions