Home > Enterprise >  I have a strange question about array php
I have a strange question about array php

Time:11-22

How to do if I have an array with 1,2,3,4,5 and I want to take IF there is 4 it will return 4. If there is no 4 it will return nothing

example i have an array from 1 to 5 $numbers = '1,2,3,4,5';

I want to take 3 i want to take 3 as 3 to match the parameter 3 and not the array id

$numbers = '1,2,3,4,5';
$array =  explode(',', $numbers);

echo $array[3]; // return 3

Array
(
    [0] => 1
    [1] => 2
    [2] => 3 // get this
    [3] => 4 // not this
    [4] => 5
)

if the array has a value of 1,2,4,5 and I'm still looking for 3 to say nothing

$numbers = '1,2,4,5';
$array =  explode(',', $numbers);

echo $array[3]; // null
Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 5
)

Or simply looking for an abbreviation of this code

<?php 
$arrays =  explode(',', $aa['cat']);
$setCat1 = false;
$setCat2 = false;

foreach ($arrays as $array)
{
    if($array == 1){
        $setCat1 = true;
    }
    if($array == 2){
        $setCat2 = true;
    }
}

CodePudding user response:

I'm not sure what problem you're trying to solve, but I think this will do what you're asking for. Use in_array() to see if a value is contained in an array.

<?php                                                                                                                                                               
$numbers = '1,2,3,4,5';                                                                                                                                             
$array =  explode(',', $numbers);                                                                                                                                   
                                                                                                                                                                    
$wanted_value = 3;                                                                                                                                                  
$output = in_array($wanted_value, $array) ? $wanted_value : NULL;                                                                                                   
echo $output;  
  • Related