Adam Ramadhan
Adam Ramadhan

Reputation: 22810

get a string from an array in php

array
  0 => string 'profile' (length=8)
  1 => string 'helloworld' (length=8)
  2 => string 'string2' (length=7)

// lets say we have an defined string that we want to split it out. or make it disappear.

string 'profile' (length=8)

how can we just get helloworld and string2 in an array from the array useing the string we defined ? ( get the a defined string out of the array ) is there a good function for this problem ?

the result should be like

array
  1 => string 'helloworld' (length=8)
  2 => string 'string2' (length=7)

Thanks for looking in

Adam Ramadhan

Upvotes: 0

Views: 4861

Answers (5)

fabrik
fabrik

Reputation: 14365

You can use array_filter() as well:

$array    = ['profile', 'helloworld', 'string2'];
$ignore   = 'profile';
$filtered = array_filter(
    $arr,
    function ($i) use ($ignore) {
        return $i !== $ignore;
    }
);

Upvotes: 0

Ahmed Zain Salem
Ahmed Zain Salem

Reputation: 47

Seems like you’re printing something expecting it to be a string, but the value is actually an array.

So, if it’s going to be an array always, you may print all items comma separated -

echo implode(", ", $yourVar);

Or, it’s can be an array sometimes, you may concat conditionally-

 echo is_array($yourVar)? implode(", ", $yourVar) : $yourVar;

Upvotes: -2

seriousdev
seriousdev

Reputation: 7656

The easiest way:

$array = array(
    'profile',
    'helloworld',
    'string2'
);

$str = 'profile';

$array = array_flip($array);
unset($array[$str]);
$array = array_flip($array);

// Array
// (
//     [1] => 'helloworld',
//     [2] => 'string2'
// )

Upvotes: 3

Nanne
Nanne

Reputation: 64399

$yourDefinedString = "profile";
foreach($yourArray as $myArray){
   if($myArray != $yourDefinedString){
      echo $myArray;
   }
}

Some variations possible, depending on how you would handle this array:

array
  0 => string 'profile' (length=8)
  1 => string 'helloworld' (length=8)
  2 => string 'anotherString' (length=8)

This example would print

helloworldanotherString

You could add newlins or spaces of course

after your edit: You could just remove stuff by getting the difference between two arrays? You could even remove more than just one string:

$theOffendingStrings = array("yourString");
$result = array_diff($youArray, $theOffendingStrings);

Upvotes: 3

Kshitiz Ghimire
Kshitiz Ghimire

Reputation: 1716

echo $var[1] will display hello world, where $var is the variable your are doing var_dump($var) now.

Upvotes: 1

Related Questions